Hi
I wanted to programmaticall y disable events like SelectedIndexCh anged without
using a boolean flag, which indeed I find a quick and dirty solution. So, I
found a
piece of code that do this more elegant:
* How to disable event in C#?
Link: http://tinyurl.com/alsge
Group: microsoft.publi c.dotnet.framew ork.compactfram ework
But I saw it is limited to ComboBoxes and to the SelectedIndexCh anged Event
and
I want to generalize it to an object of type control and to every possible
event. To
give you an idea, I will post some of my ugly code:
public static EventHandler DisableSelected IndexChanged(Co ntrol control)
{
FieldInfo fieldInfo;
object fieldObject;
EventHandler handler = null;
fieldInfo = control.GetType ().GetField("Se lectedIndexChan ged",
BindingFlags.In stance | BindingFlags.No nPublic);
if (fieldInfo != null)
{
fieldObject = fieldInfo.GetVa lue(control);
if (fieldObject is EventHandler)
{
handler = (EventHandler)f ieldObject;
//This is the part I want to avoid
if (control is ComboBox)
((ComboBox)cont rol).SelectedIn dexChanged -= handler;
else if (control is ListBox)
((ListBox)contr ol).SelectedInd exChanged -= handler;
else if (control is ListView)
((ListView)cont rol).SelectedIn dexChanged -= handler;
else if (control is TabControl)
((TabControl)co ntrol).Selected IndexChanged -= handler;
}
}
return handler;
}
Is it possible to avoid the casting and get a pointer to the
SelectedIndexCh anged
property, then apply the -= operation over it? How? As I could understand,
FieldInfo.GetVa lue(control) only returns the handler, but not the
SelectedIndexCh anged property.
Thanks in advanced,
Josef