converting string to a control name in C# [duplica

2019-04-14 22:56发布

问题:

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?

回答1:

A very optimist approach would be

this.Controls.Find("variableName", true)[0].BackColor


回答2:

Try something like this:

var txtBox = this.Controls.Find("textBox4", true);


回答3:

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.