Hadron
Hadron

Reputation: 501

Get source of event in C# Windows Forms

I have a list of string with which I want to create a menu of ToolStripItem (neither the list size nor its content is know at debug) and I want each item to execute the same event, so I go through the list with that code:

foreach (string i in items)
{
    ToolStripItem item = (ToolStripItem)toolStripMenuItem1.DropDownItems.Add(i);
    item.Click += new EventHandler(item_Click);
}

the problem is that in the item_Click method I need to know which of the above items triggered the event. If I were in WPF, I would have used RoutedEventArgs and its .Source proprety but since I am only in a regular Windows Forms app, I'm not quite sure how to do it. Is there a simple way to do it? Thank you.

Upvotes: 0

Views: 451

Answers (1)

Selman Genç
Selman Genç

Reputation: 101681

Use sender parameter in your click event

var item = sender as ToolStripItem;
if(item != null)
{
    ...
}

Upvotes: 1

Related Questions