2013-01-07 116 views
1

阅读动态创建的文本框的文本。如果我动态创建这样一个文本框:C#与其他梅索德

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; 
} 

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

预先感谢您

回答

1

必须声明texbox的方法的,它必须是全球性的。那么你可以达到框对象

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

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

0

假设这是一个Windows窗体,您可以遍历Controls可枚举对象的集合,如TabControl。下面是一些从项目我工作,适用于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 
      } 
     } 
    } 
} 
+0

不能你只需要调用'.FindControl(..)'有问题的文本? –

+0

啊几乎,答案[这里](http://stackoverflow.com/questions/4483912/find-a-control-in-c-sharp-winforms-by-name)描述了一个'.Find(..)'方法大概是像“TabControl”这样的可枚举容器。不确定'FindControl',它可能只适用于ASP .NET吗? –

+0

是的,这个问题并不确定它是ASP.NET/web还是Windows窗体......并且是 - “.FindControl()”特定于ASP.NET –

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