3

Possible Duplicate:
Find a control in C# winforms by name

Imagine that we have 4 textBoxes (and a button):

textBox1:( Here we must enter the name of the textBox where we want to change background)

textBox2:()

textBox3:()

textBox4:()

In our first textbox we enter a name of any other TextBox and when we click on a button - backrground will change accordingly.

Normally I'd do something like this:

private void button1_Click(object sender, EventArgs e)
{
string variableName = textBox1.Text();

if (variableName == "textBox1")
{
    textBox1.BackColor = Color.Black;
}
else if (variableName == "textBox2")
{
    textBox2.BackColor = Color.Black;
}
else if (variableName == "textBox3")
{
    textBox3.BackColor = Color.Black;
}
else if (variableName == "textBox4")
{
    textBox4.BackColor = Color.Black;
}
}

Another way - much simpler way do the same operation would be this:

private void button1_Click(object sender, EventArgs e)
{
    string variableName = textBox1.Text();
    variableName.BackColor = Color.Black;
}

And that's all! So my question is:

Is it possible to convert strings to "control names" as showed in example?

Community
  • 1
  • 1
Alex
  • 4,607
  • 9
  • 61
  • 99

3 Answers3

11

A very optimist approach would be

this.Controls.Find("variableName", true)[0].BackColor
Andre Calil
  • 7,652
  • 34
  • 41
3

Try something like this:

var txtBox = this.Controls.Find("textBox4", true);
Peter Kiss
  • 9,309
  • 2
  • 23
  • 38
0

You could create a Dictionary<string, TextBox> where the name of each TextBox in the Dictionary is the key for that TextBox.

Then it would be as simple as TextBoxDictionary[variableName].BackColor = Color.Black;, although I recommend checking to make sure it is actually in the dictionary before doing that.

yoozer8
  • 7,361
  • 7
  • 58
  • 93