首页 新闻 搜索 专区 学院

.net 动态添加Button 并添加Click事件 但是这个事件要点击2次才会触发。

0
悬赏园豆:5 [已关闭问题] 关闭于 2012-04-25 10:15

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Button aaa = new Button();
        aaa.Text = "11111";
        aaa.Width = 90;
        aaa.Height = 100;
        aaa.Click += new EventHandler(aaa_Click);
        this.Page.Form.Controls.Add(aaa);
        if (!IsPostBack)
        {
            Dictionary<string, DataTable> dic = new Dictionary<string, DataTable>();
            ViewState["dic"] = dic;
        }
        else
        {
            Bind();
        }
    }

    void aaa_Click(object sender, EventArgs e)
    {
        Response.Write("111");
    }
    private void Bind()
    {
        Dictionary<string, DataTable> dic = (Dictionary<string, DataTable>)ViewState["dic"];

        int j = 0;
        foreach (string item in dic.Keys)
        {
            Panel div1 = new Panel();
            int left = 400 + j * 100;
            div1.Style.Add("top", "400px");
            div1.Style.Add("left", left + "px");
            div1.Style.Add("position", "absolute");
            div1.Width = 100;
            div1.Height = 200;
            GridView gv1 = new GridView();
            Button btn = new Button();

 

            div1.Controls.Add(gv1);
            div1.Controls.Add(btn);
            div1.Visible = true;

            btn.Width = 60;
            btn.Height = 60;
            btn.Text = "确定";
            btn.Click += new EventHandler(btn_Click);


            TemplateField templateId = new TemplateField();
            templateId.ItemTemplate = new ItemTemplate("lblID", "ID");
            templateId.HeaderText = "编号";

            TemplateField templateNeiRong = new TemplateField();
            templateNeiRong.ItemTemplate = new ItemTemplate("lblNeiRong", "内容");
            templateNeiRong.HeaderText = "内容";

            CommandField command = new CommandField();
            command.ButtonType = ButtonType.Image;
            command.DeleteImageUrl = "a.jpg";
            command.ShowDeleteButton = true;

            gv1.ID = item;
            gv1.AutoGenerateColumns = false;
            gv1.Columns.Add(templateId);
            gv1.Columns.Add(templateNeiRong);
            gv1.Columns.Add(command);
            gv1.RowDeleting += new GridViewDeleteEventHandler(gv1_RowDeleting);
            gv1.PageIndexChanging += new GridViewPageEventHandler(gv1_PageIndexChanging);
            gv1.DataSource = dic[item];
            gv1.DataBind();
            Page.Form.Controls.Add(div1);
            j++;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        Dictionary<string, DataTable> dic = (Dictionary<string, DataTable>)ViewState["dic"];

        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected == true)
            {
                #region 拥有Keys值
                DataTable dt = CreateTable(item.Text);
                if (dic.Keys.Contains("Grid_" + item.Text))
                {

                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow dr1 = dic["Grid_" + item.Text].NewRow();
                        dr1.ItemArray = dr.ItemArray;
                        dic["Grid_" + item.Text].Rows.Add(dr1);
                    }
                    ViewState["dic"] = dic;
                    Bind();
                    return;
                }
                #endregion
                #region 没有keys
                else
                {
                    Panel div1 = new Panel();
                    int left = 400 + dic.Count * 100;
                    div1.Style.Add("top", "400px");
                    div1.Style.Add("left", left + "px");
                    div1.Style.Add("position", " absolute");
                    div1.Width = 100;
                    div1.Height = 200;
                    GridView gv1 = new GridView();
                    Button btn = new Button();


                    div1.Controls.Add(gv1);
                    div1.Controls.Add(btn);
                    div1.Visible = true;

                    btn.Width = 60;
                    btn.Height = 60;
                    btn.Text = "确定";
                    btn.ID = "btnConfirm";
                    btn.Click += new EventHandler(btn_Click);
                   


                    TemplateField templateId = new TemplateField();
                    templateId.ItemTemplate = new ItemTemplate("lblID", "ID");
                    templateId.HeaderText = "编号";

                    TemplateField templateNeiRong = new TemplateField();
                    templateNeiRong.ItemTemplate = new ItemTemplate("lblNeiRong", "内容");
                    templateNeiRong.HeaderText = "内容";

                    CommandField command = new CommandField();
                    command.ButtonType = ButtonType.Image;
                    command.DeleteImageUrl = "a.jpg";
                    command.ShowDeleteButton = true;

                    gv1.ID = "Grid_" + item.Text;
                    dic.Add(gv1.ID, dt);
                    gv1.DataSource = CreateTable(item.Text);

                    gv1.AutoGenerateColumns = false;
                    gv1.Columns.Add(templateId);
                    gv1.Columns.Add(templateNeiRong);
                    gv1.Columns.Add(command);
                    gv1.RowDeleting += new GridViewDeleteEventHandler(gv1_RowDeleting);
                    gv1.PageIndexChanging += new GridViewPageEventHandler(gv1_PageIndexChanging);

                    gv1.DataBind();
                    Page.Form.Controls.Add(div1);
                }
                #endregion

                ViewState["dic"] = dic;
                break;
            }
        }
    }
    void btn_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        GridView gv1 = btn.Parent.Controls[0] as GridView;
        Response.Write(gv1.ID);
    }
    private DataTable CreateTable(string name)
    {
        if (name == "aaa")
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("内容", typeof(string));
            for (int k = 0; k < 5; k++)
            {

                dt.Rows.Add(new object[] { k, "yoyo" });
            }
            return dt;
        }
        if (name == "bbb")
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("内容", typeof(string));
            for (int k = 0; k < 6; k++)
            {

                dt.Rows.Add(new object[] { k, "xulu" });
            }
            return dt;
        }
        else
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("内容", typeof(string));
            for (int k = 0; k < 7; k++)
            {

                dt.Rows.Add(new object[] { k, "徐璐" });
            }
            return dt;
        }
    }
    /// <summary>
    /// 页索引变化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void gv1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        // throw new NotImplementedException();
    }
    /// <summary>
    /// 删除事件处理方法
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView gv1 = (GridView)sender;
        string id = (gv1.Rows[e.RowIndex].FindControl("lblID") as Label).Text;
        Dictionary<string, DataTable> dic = (Dictionary<string, DataTable>)ViewState["dic"];
        DataTable dt = dic[((GridView)sender).ID];
        foreach (DataRow item in dt.Rows)
        {
            if (item["ID"].ToString() == id)
            {
                item.Delete();
                break;
            }
        }
        gv1.DataSource = dt;
        gv1.DataBind();
        dic[((GridView)sender).ID] = dt;

        ViewState["dic"] = dic;
    }
    private class ItemTemplate : ITemplate
    {
        private string _id;
        private string _field;
        public ItemTemplate(string id, string field)
        {
            this._id = id;
            this._field = field;
        }

        public void InstantiateIn(Control container)
        {
            Label lb = new Label();
            lb.ID = _id;
            lb.DataBinding += delegate(object sender, EventArgs e)
            {
                object dataItem = ((sender as Control).NamingContainer as GridViewRow).DataItem;
                lb.Text = (dataItem as DataRowView)[_field].ToString();
            };
            container.Controls.Add(lb);

        }
    }
}

 

 

前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript">

        i = 0;
        /*添加div*/
        function add() {
            //创建一个div  
            var my = document.createElement("div");
            //添加到页面  
            document.body.appendChild(my);
            //通过样式指定该div的位置方式,若是想要自己设置div的位置,这句话必须有,把它注释掉你就可以知道效果拉~试试看  
            my.style.position = "absolute";
            my.id = i;
            //通过样式指定x坐标(随机数0~450)
            my.style.top = 450;
            //通过样式指定y坐标(随机数0~700)
            my.style.left = 700 + i * 100;
            //通过样式指定宽度  
            my.style.width = 100;
            //通过样式指定高度  
            my.style.height = 100;
            //通过样式指定背景颜色,,若是背景图片 例为my.style.backgroundImage="url(img/3.jpg)"  
            my.style.backgroundColor = "#ffffcc";
            //添加div的内容  
            my.innerHTML = i++;
        }  


    </script>
</head>
<body>
    <form runat="server">
    <div>
        <asp:Button runat="server" Text="添加"
            onclick="Button1_Click" />
        <asp:Button runat="server" Text="Button" />
        <asp:ListBox runat="server">
            <asp:ListItem>aaa</asp:ListItem>
            <asp:ListItem>bbb</asp:ListItem>
            <asp:ListItem>ccc</asp:ListItem>
        </asp:ListBox>
    </div>

    </form>
</body>
</html>

btg.yoyo的主页 btg.yoyo | 初学一级 | 园豆:67
提问于:2012-04-24 22:44
< >
分享
所有回答(4)
0

后面的逻辑太复杂了(代码比较凌乱)我没仔细看,但首次运行应该是可以的啊,我的DEMO:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Button aaa = new Button();
        aaa.Text = "11111";
        aaa.Width = 90;
        aaa.Height = 100;
        aaa.Click += new EventHandler(aaa_Click);
        this.Page.Form.Controls.Add(aaa);
    }

    protected void aaa_Click(object sender, EventArgs e)
    {
        Response.Write("111");
    }
}

是正常的

artwl | 园豆:16526 (专家六级) | 2012-04-24 23:02
0

http://www.cnblogs.com/hanbing768/articles/947158.html

请研读此文章。跟生命周期是有关系的。

forhells | 园豆:969 (小虾三级) | 2012-04-25 00:23
0

你的代码本身应该没问题,但也没细看更没调试,我想出现这个问题的原因可能是放置的位置不对。

在ASP.NET中,如果要添加控件到UI,那是在Init事件中进行处理的,这个事件还衍生了另外的两个事件BeforeInit、AfterInit,BeforeInit事件的绑定可以让我们在UI进行预初始化的时候进行相关数据处理。AfterInit则让我们在UI初始化完成后进行相关处理。而Init可以说等同AfterInit,但在AfterInit之前。(以前,没有AfterInit和BeforeInit事件,我通常都是通过重载OnInit这个事件处理函数来实现BeforeInit和AfterInit)。

作为一个习惯以及遵循ASP.NET的规范,非必要,请把动态添加控件的过程放在AfterInit事件中。

如果你对ASP.NET的原理了解的话,事实上,在AfterInit和Load事件之间,.NET还做了很多事情,包括ViewState的处理、Post提交表单的数据与控件的绑定等。

把握一点:ASP.NET并没有改变HTML的任何规范,只是提供了一个封装,将我们在网站开发过程中应该遵循的数据处理流程等进行强行的分段,从而形成一个一致的开发规范。

如果你有兴趣,可以去了解下ASP程序的开发,然后比对ASP.NET,你会收获很多的。

无之无 | 园豆:5085 (大侠五级) | 2012-04-25 09:04

感谢您打了这么多的字。 我也知道你说的这些。 但是能麻烦你看看我的代码,嘛? 就复制一下就行了

支持(0) 反对(0) btg.yoyo | 园豆:67 (初学一级) | 2012-04-25 09:31

@btg.yoyo: 添加控件的代码一样,只是把这个代码放置到AfterInit中。但在处理上,好像有个细节,具体的我忘记了,你可以参考我的几篇文章,就在这个园子里。

只有在Init这个事件(包括BeforeInit和AfterInit)里构建了控件,系统才会对PostBack的事件处理进行激活。

你把构建过程放在Load事件里,此时,.net系统的事件绑定与激活操作已经完成,所以不会执行你定义的事件。

其实,所谓的ButtonClick事件不过是一个PostBack,当点击这样的Button(submit类型)的时候,会把这个事件的一些内容PostBack给服务器,.net分析这些内容,最后确定是某一个Button被点击了,然后执行ButtonClick处理。

支持(0) 反对(0) 无之无 | 园豆:5085 (大侠五级) | 2012-04-25 10:06
0

为ID 加上一个唯一的ID

btg.yoyo | 园豆:67 (初学一级) | 2012-04-25 10:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册