为什么我的第二个subButton不起作用?

时间:2014-03-31 17:04:14

标签: c# asp.net

此网页创建控件。 第一个控制"父母" 第二控制"孩子"。子按钮由父级创建。但我有一个问题,Page不回应儿童事件((

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    namespace WebApplication14
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            private Button[] buttons = new Button[256];
            protected void Page_Load(object sender, EventArgs e)
            {

也许我对这部分有问题???

for (int i = 0; i < 10; i++) // Create 10 buttons
                {
                    buttons[i] = new Button(); // New button
                    buttons[i].ID = "Button" + i; // Button id
                    buttons[i].Text = "Button " + i; // Button text

我不知道为什么这个事件不能正常工作

                buttons[i].Click += (c, cArgs) => //Set Event
                    {
                        TextBox1.Text += "Hi"; //Doesn't show me result.Why???
                    };
            }
            int val = 0;
            Button b = new Button(); // Create new button
            b.ID = "BT1"; // Set button id "BT1"
            b.Text = "Click"; // Set on button text
            form1.Controls.Add(b); // add this button to form1
            b.Click += (k, kArgs) => // Give this button event with parameters
                {
                    val = Convert.ToInt32(TextBox1.Text); // Convert value of TextBox1  to int32 and set this value to variable "val"
                    form1.Controls.Add(buttons[val]); // Add subButton by value seted on variable "Val"
                };
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为最好在页面完全加载(Page_Load)之前将所有UI对象及其事件绑定/添加到表单中,最好是在页面初始化(Page_Init)。您当前的方法没有正确绑定按钮的单击事件,因为它发生在按钮“b”上发生单击事件后的Page_Load之后。要缓解这种情况,您应该在Page_Init期间添加所有UI对象,或者如果您必须Page_Load但是您可以控制其可见性。这样,您可以保证所有对象的事件都正确绑定到表单:

C#Code-Behind:

  protected void Page_Load(object sender, EventArgs e)
  {
      for (int i = 0; i < 10; i++) // Create 10 buttons
      {
          buttons[i] = new Button(); // New button
          buttons[i].ID = "Button" + i; // Button id
          buttons[i].Text = "Button " + i; // Button text

          buttons[i].Click += (c, cArgs) => //Set Event
          {
             TextBox1.Text += "Hi";
          };

          buttons[i].Visible = false; // Set visibility to false
          form1.Controls.Add(buttons[i]); // Add button to form1
      }

      int val = 0;
      Button b = new Button(); // Create new button
      b.ID = "BT1"; // Set button id "BT1"
      b.Text = "Click"; // Set on button text
      form1.Controls.Add(b); // add this button to form1
      b.Click += (k, kArgs) => // Give this button event with parameters
      {
          val = Convert.ToInt32(TextBox1.Text); // Convert value of TextBox1  to int32 and set this value to variable "val"
          buttons[val].Visible = true; // Set visibility to true
      };
  }