Reusable event handler - identify sender

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.
 
L

Lebesgue

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);
}
}
 
G

Guest

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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top