multiurlclick
multiurlclick

Reputation: 23

C# WinForm multiple click event handlers for similar function

I have a few toolStripMenuItems that act as a useful links for a series of websites, a rough example of the code would be something like:

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    Process.Start("http://www.google.com");
}

private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
    Process.Start("http://www.bing.com");
}

private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
    Process.Start("https://www.duckduckgo.com");
}

private void toolStripMenuItem4_Click(object sender, EventArgs e)
{
    Process.Start("http://www.yahoo.com/");
}
...

Is there a more elegant way to handle this?

Upvotes: 2

Views: 1524

Answers (4)

ds-b
ds-b

Reputation: 361

You can also subscribe to click event using a lambda expression:

toolStripMenuItem1.Click += (_, __) => Process.Start("process1");
toolStripMenuItem2.Click += (_, __) => Process.Start("process2");

Upvotes: 0

DrewJordan
DrewJordan

Reputation: 5314

The first thing to do is use the same handler for each one:

toolStripMenu1.Click += toolStripItemClick;
toolStripMenu2.Click += toolStripItemClick;
// etc

I would use the Tag property for this, set it when you're constructing the toolStripItems:

toolStripMenu1.Tag = "http://www.google.com";

And then define your handler:

private void toolStripItemClick(object sender, EventArgs e)
{
    var c = (ToolStripMenuItem)sender;
    Process.Start(c.Tag.ToString());
}

Upvotes: 3

Omkommersind
Omkommersind

Reputation: 295

Put urls in menu items tag and attach this handler to all of them (hope it works)

private void toolStripMenuItemClick(object sender, EventArgs e)
{
    Process.Start(sender.Tag.ToString());
}

Upvotes: 6

KDecker
KDecker

Reputation: 7148

"Mash" all of the event handlers into one and then use the sender to see what ToolStripMenuItem was clicked.

private void toolStripMenuItem_Click(object sender, EventArgs e)
{
    if(sender == toolStripMenuItem1)
        Process.Start("http://www.google.com");
    else if(sender == toolStripMenuItem2)
        Process.Start("http://www.bing.com");
    else if(sender == toolStripMenuItem3)
        Process.Start("http://www.duckduckgo.com");
    else if(sender == toolStripMenuItem4)
        Process.Start("http://www.yahoo.com");
}

Or as Artem notes use the Tag member of the Control to store the String representing which site to visit. Then cast the sender.Tag to a String and use it.

toolStripMenuItem1.Tag = "http://www.google.com";
toolStripMenuItem2.Tag = "http://www.bing.com";
toolStripMenuItem3.Tag = "http://www.duckduckgo.com";
toolStripMenuItem4.Tag = "http://www.yahoo.com";
...
private void toolStripMenuItem_Click(object sender, EventArgs e)
{
    Process.Start(sender.Tag.ToString());
}

Upvotes: 2

Related Questions