Grixxly
Grixxly

Reputation: 464

Dynamically creating controls based on variable

First off I'm actually a DBA and not a web developer so... what I write will probably look ugly. I am building a website (they asked me if I'd try /shrug) and I have 168 checkboxes that have the same action when checked. But these actions, though the same, are performed on different controls (related to the checkbox). Instead of having a switch statement with 168 conditions can I do something like the following?

CheckBox myCB = (CheckBox)(sender);

String mySTR = myCB.ID.ToString();
String myGVstr = “gv” + mySTR.Substring(mySTR.IndexOf(‘cb’) + 1);
String myBTNstr = “btn” + mySTR.Substring(mySTR.IndexOf(‘cb’) + 1);

GridView myGV = myGVstr;
Button myBTN = myBTNstr;

// Do what I need to do with these controls
...

Upvotes: 2

Views: 121

Answers (1)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26078

This really doesn't seem like a plausible thing to do. Maybe on loading you can place all your controls into a large array? It would take 1 large section of code to place each control into the array but afterwards you can access them in a similar (more reliable) fashion.

If you insist on doing it this way the 'FindControl' method might be of some use.

http://msdn.microsoft.com/en-us/library/486wc64h.aspx

Something like...

GridView myGV = (GridView)FindControl(myGVstr)

Not tested, but might work.

Upvotes: 1

Related Questions