简体   繁体   中英

C# sender problems

I have 4 buttons and I have linked everyone to the same method in the code.

Now i wanna check which button that has been pressed, by using the code:

if(sender == button1)
 {
  //something
  }

It seems like sender gives the text of the button that has been pressed, i would like the sender to give the name of the button!

Thanks!

Cast to button:

    private void button1_Click(object sender, EventArgs e)
    {
        Button clickedButton = (Button) sender;
    }

You can then test if the button clicked is THE button.

if you want to use a if statement:

string Name = ((Button)sender).Name;
if(Name == "somename")
{
    //somecode
}

sender is the object that fired the event (in your case, a Button object), not the value of a property of the object. If you really need to write code that checks the Name property of a control (which I would advise against for future maintenance reasons...) you will need to cast it like so:

switch(((Button)sender).Name)
{
    case "whatever":
        break;
    // more here
}

The debugger is your friend here. You can set a breakpoint inside your method to inspect the object that is being passed in.

Can't you cast it to "Button" and use the "Name" property (of System.Windows.Forms.Control)?

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.name.aspx

Usually you do not have to check the sender of an event handler because it is assumed that your senders have unique meaninga and therefore unique event handlers. If you're tempted to shove all functionality in one event handler it's a bad practice. You will end up with code that is not maintainable.

However, every rule has exceptions, and in some cases it makes sense to reuse an event handler for multiple senders. In this case you can either cast or use is/as operators to identify the sender:

private void OnButtonClick(object sender, EventArgs args)
{
    Button button = (Button)sender;
    //or
    Button button = sender as Button;
    if (button != null)
    {
    ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM