Reusable event handler - identify sender

  • Thread starter Thread starter Me
  • Start date Start date
M

Me

My form has a dynamically populated context menu, and each has the same
event handler for the click event.

The event need to write the text of the clicked menu item into a
database, so I need to either pass that to the event handler, which I
cannot figure out how to do, or access the properties of the sender,
which I also cannot figure out how to do.

The context menu items are a list extracted from a database, using the
code below in a while loop:

ToolStripItem itm = cmenTicker.Items.Add(reader.GetString(0));
itm.Click += new System.EventHandler(this.itm_Click);

This is the itm_click:

private void itm_Click(object sender, EventArgs e)
{
//Balloon(/*This is where I need to know the text because
Balloon wants a string*/);
}

Sure this can't be so difficult, but I can't work this out.
 
You can cast the sender variable to the type you know the sender has.
Try this:

private void itm_Click(object sender, EventArgs e)
{
ToolStripItem itm = sender as ToolStripItem;
if (itm != null)
{
Balloon(itm.Text);
}
}
 
Me said:
My form has a dynamically populated context menu, and each has the same
event handler for the click event.
.....
This is the itm_click:

private void itm_Click(object sender, EventArgs e)
{
//Balloon(/*This is where I need to know the text because
Balloon wants a string*/);
}

Sure this can't be so difficult, but I can't work this out.

Use the TAG property of all objects that trigger the event to store an
object reference of your choice you can identify. In your event function do
this:

private void itm_Click(object sender, EventArgs e)
{
MyIdentificationObject tagobj =
(MyIdentificationObject)(((Control)(sender)).Tag);
// do what ever you want to do with tagobj.
}

best
doc
 
Lebesgue said:
You can cast the sender variable to the type you know the sender has.
Try this:

private void itm_Click(object sender, EventArgs e)
{
ToolStripItem itm = sender as ToolStripItem;
if (itm != null)
{
Balloon(itm.Text);
}
}

Yes, if you know the classtype of the senders this is easier than my solution.

doc
 
Back
Top