How do I pass parameters to events? [closed]

2019-07-21 12:39发布

问题:

Some of my variables are not getting serialized each method invocation.

How do I know where arguments go?

public static int button21_Click(object me, EventArgs MyArgs) {
  button17(me, MyArts);
}

回答1:

I admit that I am not entirely certain what you are asking, but from what I can see, you appear to be trying to use the same event handler for multiple Button.Click events. You can do this in two ways.

1. Using the WinForms designer.

Select one of your buttons then hit F4 or go to the Properties window and select the Events tab (it's the one with the icon that looks like a lightning bolt). Then find the Click event and create a new handler. Then go to each of the other buttons and find their Click event and just use the dropdown to select the handler you already created.

2. Using code.

In code, create an event handler, then add that event handler to each button's Click event.

private void OnClick(object sender, EventArgs args)
{
    // Do stuff to handle the event.
}

// This is the form's constructor.
public MyWinForm()
{
    InitializeComponents();

    this.button1.Click += OnClick;
    this.button2.Click += OnClick;
    this.button3.Click += OnClick;
    this.button4.Click += OnClick;
    this.button5.Click += OnClick;
    this.button6.Click += OnClick;
    this.button7.Click += OnClick;
}


回答2:

I was about to just write some kind of canned-response that firstly pointed out that I voted to close the question, and secondly made some derogatory remark about your English and the fact that one has to be a mind-reader to even get what you're talking about. Then I thought to hell with it, let's have a shot.

I'll ignore the fact that, in your code, button17(me, MyArts); makes no sense at all. I assume you want to raise an event on it, or pass the arguments on, to another button. Firstly you've put MyArts instead of MyArgs, so there's a compilation error right here. Secondly, button17 is likely already constructed and doesn't need constructing again. I suspect your actual motive is to call some other method on it, passing the arguments on.

Thirdly, this method is static. So if it is a member of a class, it has no access to any member-variables of it, so when it does get called, this is not valid and you're in the global namespace without a paddle. Consider making it non-static.

Hope this helps. I know bikers that wouldn't try and answer this.