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.
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 = "";
}
}
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";
}
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";
}
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";
}
As the goal is to reduce code size, no, you can't do that. Near to what you are trying to achieve would be:
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 = "";
}
}