Chase Ernst
Chase Ernst

Reputation: 1155

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!

Upvotes: 0

Views: 1802

Answers (3)

Chase Ernst
Chase Ernst

Reputation: 1155

I came to the answer with help from @paqogomez. He suggested I use the ItemCommand event handler for the ListView to get the button that is being clicked for the listview.

Inside the ItemCommand event handler I checked them command argument and used the appropriate code thereafter.

protected void LV_Tickets_ItemCommand(object sender, ListViewCommandEventArgs e)
{
    if(e.CommandName == "Update")
    {
        //code here
    }
}

Upvotes: 1

Sherif Ahmed
Sherif Ahmed

Reputation: 1946

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
}

Upvotes: 1

Roman Kotenko
Roman Kotenko

Reputation: 516

The sender seems to be your ListView, not Button. Try using Button_OnClick event instead of ListView_ItemCancelling.

Or try doing some reseach on ListView_ItemCancelling, such as using ListViewCancelEventArgs e parameter, maybe it can help you in this situation. You can read more about it on MSDN.

Upvotes: 0

Related Questions