Finding out which button was clicked in a SelectedIndexChanged event handler of a GridView
-
11-12-2019 - |
Question
We have a GridView that contains 2 "Select" buttons for each row that is displayed in the GridView.
We would like to know if there is a way to find out which of the 2 buttons was clicked on by using the SelectedIndexChanged handler.
This coding shows the buttons we have:
<asp:UpdatePanel
ID="UpdatePanelParentsSummary"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<p>Parent Search:
<asp:TextBox
ID="TextBoxSearch"
runat="server"
Width="207px"
Text="ALL"> </asp:TextBox>
<asp:Button
ID="ButtonSearch"
runat="server"
Text="Search" />
<asp:Button
ID="ButtonSearchAll"
runat="server"
Text="Show ALL Parents" />
<br />
</p>
<asp:GridView
ID="GridViewParentsSummary"
runat="server"
AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="ID"
>
<Columns>
<asp:BoundField
DataField="ID"
HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True" Visible="False" />
<asp:BoundField
DataField="FatherName"
HeaderText="FatherName"
SortExpression="FatherName" />
<asp:BoundField DataField="MotherName" HeaderText="MotherName"
SortExpression="MotherName" />
<asp:ButtonField
ButtonType="Button"
CommandName="Select"
Text="Select Details" />
<asp:ButtonField
ButtonType="Button"
CommandName="Select"
Text="New Person To Release Child" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
This is the code in the SelectedIndexChanged handler:
Protected Sub GridViewParentsSummary_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridViewParentsSummary.SelectedIndexChanged
IntParentsID = GridViewParentsSummary.DataKeys(GridViewParentsSummary.SelectedIndex).Value
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
Solution
Ah, there is a simple solution to this problem. Your sender is the button clicked. Just try something like:
ButtonField buttonClicked = sender as ButtonField;
if (buttonClicked != null) {
String commandName = buttonClicked.CommandName;
if (commandName.equals("Command1") {
... do something awesome ...
} else if (commandName.equals("Command2")) {
... do something less awesome ...
}
}
OTHER TIPS
I don't think you can differentiate between the source at the GridView event level because it is an event raised by the GridView at that point which is masking the lower level event. You can, however, implement a row level handler to identify which button was used to raise the event and set it up somewhere for use in the gridview event.
protected void GridView_RowCommand(object sender, CommandEventArgs e)
{
e.CommandArgument ....contains the argument name
....
}