Tracking names of dynamically generated controls
I am creating separate checkedlistbox for different sections of a database at runtime, which i got to work the way i want to, my question is how do i keep track of the names of the checkedlistboxes so that i can refer to them later in code. Say the program creates 3 boxes. how do i name them consecutively and call them further into the program in another sub?
Andrew WoosterPosted Jul 27, 2005, 12:17 PM
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebuicontrolclassfindcontroltopic.asp
kenPosted Jul 27, 2005, 11:47 AM
is there anything in c# like vb's findcontrol method? or how else can i accomplish calling a control in code that doesn't exist until runtime?
example of what doesnt work:
CheckedListBox newcheck = CheckedListBox(this.Controls(dynaname.ToString()));
where dynaname is a string containing the name of the control, i want to do this so i can use 'newcheck' to fill the control with the correct amount of checkboxes.
Andrew WoosterPosted Jul 27, 2005, 10:38 AM
A very simple way to do it is to simply have 3 variables that each track their own control. This is not a very good option because if you want to change to 4 controls then you have to create a new variable.
Another option is to realize that they are placed on the form and are stored in the .Controls accessor. You can get them out by using the typeof operator or by checking for their name. Again, not a great solution because it's not very expandable or if you change the name of the control your code might break.
Another option is to create an array of the controls and put them in there. You have to be careful with this one because if you want to access a specific control, you will have to know where in the array it is stored.
Take your pick on any of these options, or come up with your own.