Programmatically disabling Windows Control Events

DotNet77
Hi



I wanted to programmatically disable events like SelectedIndexChanged 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: tinyurl.com/alsge

Group: microsoft.public.dotnet.framework.compactframework



But I saw it is limited to ComboBoxes and to the SelectedIndexChanged 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 DisableSelectedIndexChanged(Control control)

{

FieldInfo fieldInfo;

object fieldObject;

EventHandler handler = null;



fieldInfo = control.GetType().GetField("SelectedIndexChanged",

BindingFlags.Instance | BindingFlags.NonPublic);

if (fieldInfo != null)

{

fieldObject = fieldInfo.GetValue(control);

if (fieldObject is EventHandler)

{

handler = (EventHandler)fieldObject;



//This is the part I want to avoid

if (control is ComboBox)

((ComboBox)control).SelectedIndexChanged -= handler;

else if (control is ListBox)

((ListBox)control).SelectedIndexChanged -= handler;

else if (control is ListView)

((ListView)control).SelectedIndexChanged -= handler;

else if (control is TabControl)

((TabControl)control).SelectedIndexChanged -= handler;

}

}

return handler;

}



Is it possible to avoid the casting and get a pointer to the

SelectedIndexChanged

property, then apply the -= operation over it? How? As I could understand,

FieldInfo.GetValue(control) only returns the handler, but not the

SelectedIndexChanged property.



Thanks in advanced,

Josef


-