Soliman Soliman
Soliman Soliman

Reputation: 159

How do you find textbox controls by their names from a string in C#?

Please consider the following segment of code:

 protected void displayGannt()
        {
            TextBoxT0.BackColor = getColour(time.moments[0]);
            TextBoxT1.BackColor = getColour(time.moments[1]);
            TextBoxT2.BackColor = getColour(time.moments[2]);
            TextBoxT3.BackColor = getColour(time.moments[3]);
            TextBoxT4.BackColor = getColour(time.moments[4]);
            TextBoxT5.BackColor = getColour(time.moments[5]);
            TextBoxT6.BackColor = getColour(time.moments[6]);

Is there any conceivable way of putting this segment of code into a for loop with a counter instead of having to write out a million lines of code? Are there any c# macros that could possibly do this job in a for loop of some sort? I certainly cant think of a way. Your answers are appreciated.

Upvotes: 2

Views: 208

Answers (4)

Soliman Soliman
Soliman Soliman

Reputation: 159

for (int i = 0; i < 111; i++)
{
    string currentbox = "TextBoxT" + i.ToString();
    TextBox currentTextBox = (TextBox)this.FindControl(currentbox);
    currentTextBox.BackColor = getColour(time.moments[i]);

} 

111 lines of code now become 5 lines of code and the processor has to work a little harder so you lose a bit of performance, but such is life.

Upvotes: 0

npinti
npinti

Reputation: 52185

You could use the .FindControl(String id) to get the controls you are after (if web).

for(inti i = 0; i < 7; i++)
{
    Control c = parentControl.Find("TextBoxT" + i);
    if(c != null)
    {
       c.BackColor = getColour(time.moments[i]);
    }
}

Upvotes: 0

drf
drf

Reputation: 8699

A simple solution is to reference the text boxes in an array (either at the class level or within the method), and enumerate through that array:

protected void displayGannt()
{
        var textboxes = new[] {TextBoxT0, TextBoxT1, TextboxT2, TextboxT3, TextboxT4, TextboxT5, TextboxT6};
        for (int i = 0; i < textboxes.Length; i++) 
            textboxes[i].BackColor = getColour(time.moments[i]);
}

Upvotes: 1

TGH
TGH

Reputation: 39268

var i = 0;
foreach(var txt in this.Controls.OfType<TextBox>().OrderBy(t => t.Id))
{
   txt.BackColor = getColour(time.moments[i]);
   i++;
}

Try the above

Upvotes: 5

Related Questions