如何为动态创建的按钮(为每个按钮)创建EventHandler C#VS2010

时间:2014-04-08 13:59:24

标签: c# jquery button event-handling

所以,我有一个表格,其中所有按钮,文本框和实验室都是动态生成的

代码:

private void LoadElements()
            {
                int Y = 30;
                int j = 0;
                con.Open();
                OleDbCommand populate = new OleDbCommand("SELECT * FROM Users", con);
                OleDbDataReader reader = populate.ExecuteReader();
                while (reader.Read())
                {
                    b = new Button();
                    b.Text = "Delete";
                    b.Name = reader["Username"].ToString();
                    b.BackColor = Color.DarkOrange;
                    b.ForeColor = Color.Black;
                    b.Location = new Point(240, Y);
                    b.FlatStyle = FlatStyle.Flat;
                    LB.Add(b);
                    tb1 = new TextBox();
                    tb1.Location = new Point(10, Y);
                    TB1.Add(tb1);
                    tb1.Text = reader["Username"].ToString();
                    tb2 = new TextBox();
                    tb2.Location = new Point(120, Y);
                    tb2.Text = reader["Password"].ToString();
                    TB2.Add(tb2);
                    Y += 30;
                    j++;
                }

                foreach (Button BTN in LB) // <- this is a globaly declared List<Button>
                {
                    this.Controls.Add(BTN);
                    BTN.Click += new EventHandler(BTN_Click);
                }
                foreach (TextBox text1 in TB1)  // <= -||- List<TextBox>
                { this.Controls.Add(text1); }
                foreach (TextBox text2 in TB2)  // -||-
                { this.Controls.Add(text2); }

              // MORE CODE UNDER
      }

正如您可能或可能没有注意到的那样,整个表格都是&#34; superadmin&#34;表单类型,所有用户和密码都从数据库加载到它上面。我希望能够引用创建的按钮,当单击“删除”按钮时,我希望程序进入数据库并搜索&#34; WHERE [用户名] LIKE&#34; + button.Name +&#34;&#34;(因为按钮名称实际上是用户名);我的代码动态创建元素如下:[Name] [Password] [Delete]以[textbox1] [textbox2] [button]的形式。问题是每当我点击任何按钮时它只引用最后创建的那个按钮,我怎样才能使事件处理程序能够看到每个按钮的相应.name?

2 个答案:

答案 0 :(得分:1)

关键代码在事件处理过程中 - 您没有显示。查看对象发送者参数,并相应地使用它!

void BTN_Click(object sender, EventArgs e)
{
    Button b = sender as Button;
    if (b!=null)
    {
        //that's your button, with the properties created in the loop.
    }
}

答案 1 :(得分:0)

看起来你正在寻找这段代码。

b.Click += new EventHandler(b_Click);

将其添加到按钮创建中......

while (reader.Read())
            {
                b = new Button();
                b.Text = "Delete";
                b.Name = reader["Username"].ToString();
                b.BackColor = Color.DarkOrange;
                b.ForeColor = Color.Black;
                b.Location = new Point(240, Y);
                b.FlatStyle = FlatStyle.Flat;
                ***b.Click += new EventHandler(b_Click);***
                LB.Add(b);
            }