【问题标题】:C# read the text of dynamically created text box from other methodeC# 从另一个方法读取动态创建的文本框的文本
【发布时间】:2012-12-21 09:39:46
【问题描述】:

如果我像这样动态创建一个文本框:

private void Form1_Load(object sender, EventArgs e)
{
   TextBox tb=new TextBox();
   ...
   this.Controls.Add(tb);
}

如果我的表单上有一个按钮,并且我想从按钮单击事件处理程序中读取文本框的文本

private void button1_Click(object sender, EventArgs e)
{
 if(**tb.text**=="something") do something;
}

问题是我在按钮处理程序中找不到文本框控件。

提前谢谢你

【问题讨论】:

    标签: c#-4.0


    【解决方案1】:

    你必须在方法之外声明 texbox,它必须是全局的。然后你可以到达文本框对象

    TextBox tb;
    private void Form1_Load(object sender, EventArgs e)
    {
      tb=new TextBox();
      ...
      this.Controls.Add(tb);
    }
    

    【讨论】:

      【解决方案2】:

      TextBox 声明为您的Form 类私有成员。

      【讨论】:

        【解决方案3】:

        您可以遍历Controls 的可枚举对象集合,例如TabControl,假设这是一个Windows 窗体。这是我正在从事的一个项目中的一些内容,适用于TextBox

        foreach (TabPage t in tcTabs.TabPages)
        {
            foreach (Control c in t.Controls)
            {
                MessageBox.Show(c.Name);  // Just shows the control's name.
        
                if (c is TextBox)    // Is this a textbox?
                {
                    if (c.Name == "txtOne")  // Does it have a particular name?
                    {
                        TextBox tb = (TextBox) c;  // Cast the Control as a TextBox
        
                        tb.Text = "test";  // Then you can access the TextBox control's properties
                    }
                }
            }
        }
        

        【讨论】:

        • 您不能直接为有问题的文本框拨打.FindControl(..) 吗?
        • 啊,几乎,答案here 描述了一个.Find(..) 方法,大概是用于像TabControl 这样的可枚举容器。不确定FindControl,它可能只适用于 ASP .NET?
        • 是的,这个问题对于它是 ASP.NET / web 还是 Windows 窗体尚无定论......而且是的 - .FindControl() 特定于 ASP.NET
        【解决方案4】:
        private TextBox tb = new TextBox();
        private void Form1_Load(object sender, EventArgs e)
        {
          this.Controls.Add(tb);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-13
          • 2017-01-12
          • 1970-01-01
          • 2020-07-13
          相关资源
          最近更新 更多