c# - How to use reflection to cast a control as its type in order to modify properties? -


here's example of do:

book enable = false; foreach (control c in controllist) {     if (c mytextbox)     {         (c mytextbox).enabled = enable;     }     if...     ... } 

instead of having multiple if statements every type of control, there way type of control in order cast , able access , set property of control?

this great example of when not use reflection.

the control class contains enabled property can use descendants of control change enabled state. simple way change enabled state of collection of controls is:

bool enable = false; foreach (control c in controllist)     c.enabled = enable; 

or (now you've mentioned system.web.ui namespace) can webcontrol-derived objects, assuming controllist collection can contain things derive control no webcontrol:

foreach (webcontrol c in controllist.oftype<webcontrol>())     c.enabled = enable; 

reflection handy in situations , can pretty cool things it. it's verbose , kind of tough head around sometimes, , can done more other ways.

where useful if had collection of arbitrary objects of different types, of may have bool enabled property can set, there no guarantee have common base class can access enabled property on. this:

bool enabled = false; foreach (var obj in objectlist) {     var tobj = obj.gettype();     propertyinfo pienabled = tobj.getproperty("enabled", typeof(bool));     if (pienabled != null && pienabled.canwrite)         pienabled.setvalue(obj, enabled); } 

a lot more complex, bit more opaque, , much, much slower accessing property via control parent class.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -