【问题标题】:How to handle Windows Forms controls created at runtime?如何处理在运行时创建的 Windows 窗体控件?
【发布时间】:2012-09-14 13:10:29
【问题描述】:

我有一个Form,上面有两个控件,一个Button 和一个TextBox
这些控件是在运行时创建的。

当我单击Button 时,我想对TextBox.Text 属性进行一些操作。
但是,使用这段代码我不能:

 private void Form1_Load(object sender, EventArgs e)
 {
     TextBox txb = new TextBox();
     this.Controls.Add(txb);
     Button btn = new Button();
     this.Controls.Add(btn);
     btn.Click += new EventHandler(btn_Click);
 }

我正在这里寻找它:

public void btn_Click(object sender, EventArgs e)
{
    foreach (var item in this.Controls)
    {
        if (item is TextBox)
        {
            if (((TextBox)item).Name=="txb")
            {
                MessageBox.Show("xxx");
            }
        }
    }
}

【问题讨论】:

    标签: c# winforms runtime controls


    【解决方案1】:

    您没有名称为“txb”的文本框。所以,这个表达式永远是假的:if(((TextBox)item).Name=="txb")

    试试这个代码:

    private void Form1_Load(object sender, EventArgs e)
     {
         TextBox txb = new TextBox();
         txb.Name = "txb";
         this.Controls.Add(txb);
         Button btn = new Button();
         this.Controls.Add(btn);
         btn.Click += new EventHandler(btn_Click);
     }
    

    【讨论】:

      【解决方案2】:

      我会保留对您的 TextBox 的引用。

      TextBox txb;
      private void Form1_Load(object sender, EventArgs e)
       {
           txb = new TextBox();
           this.Controls.Add(txb);
           Button btn = new Button();
           this.Controls.Add(btn);
           btn.Click += new EventHandler(btn_Click);
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-17
        • 1970-01-01
        • 2012-04-22
        • 2019-04-01
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 2013-11-04
        相关资源
        最近更新 更多