Dynamic Variable Name Used in C # for WinForms

Not sure if this is the best way to articulate this, but I wonder if it is possible to access the name of a dynamic variable in C # (3.5).

Here is the code I'm currently looking to pull up or make it more elegant with a loop.

    private void frmFilter_Load(object sender, EventArgs e)
    {
        chkCategory1.Text = categories[0];
        chkCategory2.Text = categories[1];
        chkCategory3.Text = categories[2];
        chkCategory4.Text = categories[3];
        chkCategory5.Text = categories[4];
        chkCategory6.Text = categories[5];
        chkCategory7.Text = categories[6];
        chkCategory8.Text = categories[7];
        chkCategory9.Text = categories[8];
        chkCategory10.Text = categories[9];
        chkCategory11.Text = categories[10];
        chkCategory12.Text = categories[11];  


    }

Is there a way to do something like "chkCategory" + i.ToString ()). Text?

+5
source share
7 answers
for(...)
{
     CheckBox c = this.Controls["chkCategory" + i.ToString()] as CheckBox ;

     c.Text = categories[i];  
}
+5
source

Yes you can use

  Control c = this.Controls.Find("chkCategory" + i.ToString(), true).Single();
  (c as textBox).Text = ...;

Add some errors and wrap them in a nice (extension) method.


Edit: it returns Control[], so at the end you need either [0], or .Single(). Added.

+6

. .

, .

+2

:

Checkbox[] chkCataegories = new Checkbox[] { chkCategory1, chkCategory2 ... };
for(int i = 0; i < chkCategories.Length; i++)
    chkCategories[i].Text = categories[i];

:

for(int i = 0; i < categories.Length; i++)
{
    Checkbox chkCategory = new chkCategory { Text = categories[i] };
    someContainer.Controls.Add(chkCategory);
}

, .

+1

. chkCategory1 - 12 for. , chkCategory, , . , , :

private void frmFilter_Load(object sender, EventArgs e)
{
    var chkCategories = new [] { chkCategory1, chkCategory2, chkCategory3, .......... };
    for(int i = 0 ; i < chkCategories.Length ; i++ ) 
        chkCategoies[i].Text = categories[i];
}

, , , , , , , .

0

, - (, ):

private readonly CheckBox[] allMyCheckboxes = new CheckBox[] { chkCategory1, chkCategory2, ... }

for (i = 0; i < 12; i++) allMyCheckboxes[i].Text = categories[i];
0

"this.Controls [" chkCategory "+ i.ToString()]" "this.Controls.Find(" chkCategory "+ i.ToString(), true)" ... , [] int , ControlCollection Find.

"Control myControl1 = FindControl (" TextBox2 "); .

I need this form as I iterated over another array, retrieved the values ​​and used them to populate the form fields. It is much easier to search for labels1, label2, label3, etc.

0
source

All Articles