Hi everyone. I'm new to C# and trying to learn the ins and outs.
I have a menu which I want to be dynamic....so I created a test application and tried to attach a method's string name to any event. Anyone, please help me on this one. Thanks in advance.
public interface ITest
{
void SayMessage(Object aSender, EventArgs aEventArgs);
event EventHandler Click;
}
public partial class Form1 : Form, ITest
{
public event EventHandler Click;
public Form1()
{
InitializeComponent();
AttachButtonToEvent();
}
private void button1_Click(object sender, EventArgs e)
{
}
public void AttachButtonToEvent()
{
Type dClassType = typeof(Form1);
Object dInstance = this;
EventInfo dEvent = dClassType.GetEvent("Click");
Type tEventType = dEvent.EventHandlerType;
//FIRST METHOD
//This is the method I prefer, but this is returning null
MethodInfo dMethodInfo = typeof(Form1).GetMethod("SayMessage", BindingFlags.NonPublic | BindingFlags.Instance);
//SECOND METHOD
//This obviously does more work but this return the methodinfo that i'm looking for
MethodInfo dMethodInfo = null;
foreach (MethodInfo dMI in typeof(Form1).GetMethods())
{
if (dMI.Name == "SayMessage")
{
dMethodInfo = dMI;
break;
}
}
if (dMethodInfo != null)
{
//But when it reaches here, it still says "Error binding to target method."
Delegate dDelegate = Delegate.CreateDelegate(tEventType, dMethodInfo);
MethodInfo dMethodHandler = dEvent.GetAddMethod();
Object[] dMethodArgs = { dDelegate };
dMethodHandler.Invoke(dInstance, dMethodArgs);
}
}
public void SayMessage(Object aSender, EventArgs aEventArgs)
{
MessageBox.Show(textBox1.Text);
}
}