views:

104

answers:

5

Lets just say that I have three textboxes: TextBox1, TextBox2, TextBox3. Normally if I wanted to change the text for example I would put TextBox1.Text = "Whatever" and so on. For what I'm doing right now I would like to something like (TextBox & "i").Text. That obviously isn't the syntax I need to use I'm just using it as an example for what I need to do. So how can I do something like this? The main reason I'm doing this is to reduce code with a loop.

Please keep in mind that I'm not actually changing the text of the textboxes I'm simply using that as an example to get the point across.

+2  A: 

Use an array to access the TextBox objects by index:

TextBox[] textBoxes = new TextBox[3];
textBoxes[0] = textBox1;
textBoxes[1] = textBox2;
textBoxes[2] = textBox3;

for (int i = 0; i < 3; i++)
{
    textBoxes[i].Text = "Whatever";
}
dtb
A: 

As the goal is to reduce code size, no, you can't do that. Near to what you are trying to achieve would be:

  • to save the controls in a List or Array
  • loop the List or Array

    List<TextBox> myTxts = new List<TextBox> {textBox1, textBox2, textBox3};
    foreach(TextBox txt in myTxts) {
      txt.Text = "";
    }
    

Another approach would be to poll the Controls Collection of the Form

foreach(Control ctl in this.Controls) {
  var txt = ctl as TextBox;
  if (txt != null) {
     txt.Text = "";
  }
}
Jhonny D. Cano -Leftware-
A: 

I would recommend not doing this in general. Often, it's best to put your object references into a collection, and then work on the collection - or to use some other approach along those lines.

However, it is possible to do this (though it's slow) via Reflection:

var fields = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Where(f => f.Name.StartsWith("TextBox"));

foreach(var field in fields)
{
    TextBox box = field.GetValue(this) as TextBox;
    if (box != null)
        box.Text = "Whatever";
}
Reed Copsey
+1  A: 
this.Controls.OfType<TextBox>().First(r => r.ID == "textbox1").Text = "whatever";

if you know of course, that textbox with id 'textbox1' exists

or

foreach (var tb in  this.Controls.OfType<TextBox>()) {
    tb.Text ="whatever";
}
vittore
Does that work in Visual Studio **2005**?
dtb
the later without lambda should work
vittore
A: 

When you create your TextBox dynamically you can use an array of TextBoxes which is much easier.
However it is possible to use reflection, too:

var textBoxes = GetType().GetFields( BindingFlags.NonPublic | BindingFlags.Instance )
foreach( var fieldInfo in textBoxes )
{
    if( fieldInfo.FieldType == typeof( TextBox ) )
    {
        var textBox = ( TextBox )fieldInfo.GetValue( this );
        textBox.Text = "";
    }
}
tanascius
reflection is too complicated to use here , just `Controls.OfType<TextBox>()` will do =)
vittore
@vittore yes, you get my upvote!
tanascius