Search code examples
c#asp.netlistviewsender

Using sender to determine what button is pressed in ListView


I have a ListView that has Update and Cancel buttons. Both of these buttons have a CommandName of Cancel, so they fire the same ListView event handler (ListView_ItemCanceling).

Inside this event handle I execute my stored procedures. The issue I am having is since both buttons fire the same event handler they both update. Even if there are no changes being made.

I would like to try to determine the button that has fired the event at the start of the event handler (possibly using sender?), but I cannot figure out how to do this.

This is what I was currently trying to do in the ListView_ItemCancelling event handler:

Button newButton = (Button)sender;
if(newButton.Text == "Cancel")
{
     Console.Write("this worked");
}

When I execute this code I get an error message telling me that I cannot convert the sender object from ListView object to a Button object.

Any help will be greatly appreciated!


Solution

  • You can define to command names for each button to detect the which one is click for example: define the first as "Cancel1" and the other "Cancel2" and in the code you can check like that:

    if(CommandName == "Cancel1")
    {
    // do some thing
    }
    else if(CommandName == "Cancel2")
    {
    // do other staff
    }
    

    or if both at doing the same job but you need to determine the sender

    if(CommandName == "Cancel1" || CommandName == "Cancel2")
    {
    // do some thing common
    }
    
    if(CommandName == "Cancel1")
    {
    // do some thing if button 1 clicked
    }
    
    if(CommandName == "Cancel2")
    {
    // do some thing if button 2 clicked
    }