2

If I created a textbox dynamically like this:

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

and if I have a button on my form and I want to read the text of the textbox from within the button click event handler

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

The problem is that I can't find the textbox control in the button handler.

Thank you in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mkm
  • 122
  • 1
  • 9

4 Answers4

1

you have to declare texbox out of the method,it has to be global. then you can reach textbox object

TextBox tb;
private void Form1_Load(object sender, EventArgs e)
{
  tb=new TextBox();
  ...
  this.Controls.Add(tb);
}
Mustafa Ekici
  • 7,263
  • 9
  • 55
  • 75
0

Declare TextBox as your Form class private member.

Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
0

You could iterate through the Controls collection of an enumerable object like a TabControl, assuming this is a Windows form. Here's some from a project I'm working on, adapted for 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
            }
        }
    }
}
Darth Continent
  • 2,319
  • 3
  • 25
  • 41
  • Couldn't you just call `.FindControl(..)` for the textbox in question? – marc_s Jan 07 '13 at 17:52
  • Ahh almost, the answer [here](http://stackoverflow.com/questions/4483912/find-a-control-in-c-sharp-winforms-by-name) describes a `.Find(..)` method presumably for an enumerable container like the `TabControl`. Not sure about `FindControl`, might it only apply to ASP .NET? – Darth Continent Jan 07 '13 at 19:53
  • Yeah, the question isn't conclusive on whether it's ASP.NET / web or Windows forms... and yes - `.FindControl()` is specific to ASP.NET – marc_s Jan 07 '13 at 19:54
0
private TextBox tb = new TextBox();
private void Form1_Load(object sender, EventArgs e)
{
  this.Controls.Add(tb);
}
spajce
  • 7,044
  • 5
  • 29
  • 44