converting string to a control name in C#

15,508

Solution 1

A very optimist approach would be

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

Solution 2

Try something like this:

var txtBox = this.Controls.Find("textBox4", true);
Share:
15,508
Alex
Author by

Alex

Updated on June 05, 2022

Comments

  • Alex
    Alex almost 2 years

    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?

  • SearchForKnowledge
    SearchForKnowledge over 9 years
    .Find is not populating in VS for me :/
  • Andre Calil
    Andre Calil over 9 years
    @SearchForKnowledge do you have using System.Linq; on you file?
  • Syed Mohamed
    Syed Mohamed over 9 years
    not working...Error:object not set to instance...i have provided a correct control ID too
  • Andre Calil
    Andre Calil over 9 years
    @Syed This error means that the control wasn't find, thus it's returning null. Could you post some of you code?
  • sridhar rajan
    sridhar rajan about 5 years
    thanks it's working