Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to program multiple WindowsForms at once?

I got a lot of toolStripMenuItem's, and I want those to all do the same function, but with another parameter. Is this somehow possible to program in a for-loop?

So this is what I got:

    private void toolStripMenuItem1_Click(object sender, EventArgs e) 
    {
        myFunction(1);
    }

    private void toolStripMenuItem2_Click(object sender, EventArgs e)
    {
        myFunction(2);
    }

    private void toolStripMenuItem3_Click(object sender, EventArgs e)
    {
        myFunction(3);
    }

Thanks in advance

like image 760
wouter de jong Avatar asked Apr 28 '26 04:04

wouter de jong


1 Answers

Set to OnClick for the 3 controls only one method:

private void toolStripMenuItem_Click(object sender, EventArgs e) 
{
    //I suppose this is MenuItem if it something else you should write correct control

    MenuItem item = (MenuItem)sender;
    int attributeValue = 0;

    if(sender.ID == "toolStripMenuItem1")
    {
        attributeValue=1
    }
    else if (sender.ID == "toolStripMenuItem2")
    {
       attributeValue=2
    }
    else if(sender.ID == "toolStripMenuItem3")
    {
       attributeValue=3
    }

    myFunction(attributeValue);
}

If you will have strict names of your controls: toolStripMenuItem1, toolStripMenuItem2 and so on.

 MenuItem item = (MenuItem)sender;
 string numberID = string.Concat(item.ID.Where(x=> char.IsNumber(x)));
 myFunction(int.Parse(numberID));
like image 165
mybirthname Avatar answered Apr 30 '26 18:04

mybirthname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!