Dynamic Variable Name Use in C# for WinForms

前端 未结 7 1569
余生分开走
余生分开走 2021-01-13 01:28

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

7条回答
  •  再見小時候
    2021-01-13 01:46

    Sometimes it can help to put your controls into an array or collection as such:

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

    As another approach, you can dynamically create your checkboxes at runtime instead of design time:

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

    At least with dynamically created controls, you don't need to modify your GUI or your form code whenever you add new categories.

提交回复
热议问题