Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Variable Name Use in C# for WinForms

Not sure what is the best way to word this, but I am wondering if a dynamic variable name access can be done in C# (3.5).

Here is the code I am currently looking to "smarten up" or make 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?

like image 516
Awaken Avatar asked Aug 11 '10 14:08

Awaken


People also ask

What is dynamic variable in C?

A dynamic variable can be a single variable or an array of values, each one is kept track of using a pointer. After a dynamic variable is no longer needed it is important to deallocate the memory, return its control to the operating system, by calling "delete" on the pointer. Operation.

What is the use of dynamic variable?

A dynamic variable is a variable you can declare for a StreamBase module that can thereafter be referenced by name in expressions in operators and adapters in that module. In the declaration, you can link each dynamic variable to an input or output stream in the containing module.

What is a dynamic variable name?

In programming, dynamic variable names don't have a specific name hard-coded in the script. They are named dynamically with string values from other sources. Dynamic variables are rarely used in JavaScript. But in some cases they are useful.

What is static and dynamic variable in C?

When the allocation of memory performs at the compile time, then it is known as static memory. When the memory allocation is done at the execution or run time, then it is called dynamic memory allocation.


2 Answers

Yes, you can use

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

Add some errorchecking and wrap it in a nice (extension) method.


Edit: It returns Control[] so either a [0] or a .Single() are needed at the end. Added.

like image 106
Henk Holterman Avatar answered Sep 21 '22 10:09

Henk Holterman


for(...)
{
     CheckBox c = this.Controls["chkCategory" + i.ToString()] as CheckBox ;

     c.Text = categories[i];  
}
like image 30
Rony Avatar answered Sep 20 '22 10:09

Rony