0
votes

I am adding a new functionality to an old system, I need to add a new LinkButton to a GridView. How can I know which LinkButton was clicked so that I can do different things. Right now they are, of course, doing the same thing.

<asp:GridView ID="gvHabitacionesCD" runat="server" CssClass="datatable"
                    AutoGenerateColumns="False" Width="100%"
                    OnSelectedIndexChanged="gv_SelectedIndexChanged"
                    EmptyDataText="Select a Period"
                    DataKeyNames="idH">
                    <Columns>
                        <asp:BoundField HeaderText="idH" DataField="idH" Visible="false" />
                        <asp:TemplateField HeaderText="Last Name">
                            <ItemTemplate>
                                <asp:LinkButton ID="btnSelectLastName" runat="server" CommandName="Select" Text='<%# Eval("LastName") %>'></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:LinkButton ID="btnSelectName" runat="server" CommandName="Select" Text='<%# Eval("Name") %>'></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
</asp:GridView>

On CodeBehind

protected void gv_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridView gv = (GridView)(sender);
            getReservation(gv.DataKeys[gv.SelectedIndex].Value.ToString());
        }
1
I would change the CommandNames personally and add your own command handling (i.e. GridView RowCommand), so you could have a command SelectFirstName and then SelectLastName - JohnPete22
But, if you're really wanting to keep that command, look into the sender object to identify the button. docs.microsoft.com/en-us/dotnet/api/… - JohnPete22

1 Answers

1
votes

Your question should be: Whick LinkButton in Gridview was clicked?

for CommandName="Select" Make 2 different commands:

  1. CommandName="SelectLastName"
  2. CmmandName="SelectFirstName"

So the click on the each LinkButton would know what to do.

 <asp:BoundField HeaderText="idH" DataField="idH" Visible="false" />
                    <asp:TemplateField HeaderText="Last Name">
                        <ItemTemplate>
                            <asp:LinkButton ID="btnSelectLastName" runat="server" 
CommandName="SelectLastName" Text='<%# Eval("LastName") %>'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <asp:LinkButton ID="btnSelectName" runat="server" 
CommandName="SelectFirstName" Text='<%# Eval("Name") %>'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>