Passing an id value to LinkButton server side event in gridview control

DNR picture DNR · Jul 24, 2012 · Viewed 8k times · Source

I am trying to pass a CustomerID value to codebehind, from my LinkButton in my gridview control. I tried the solution suggested here but it does not work.

My gridview code is:

<asp:TemplateField HeaderText="Last Name, First Name">
    <ItemTemplate>
        <asp:LinkButton OnClick="EditCustomer" id="lbtnCustomerName" CommandName="CustomerName" Visible="true" runat="server" ToolTip="Click to edit customer."><%# DataBinder.Eval(Container.DataItem, "custLastName") + ", " + DataBinder.Eval(Container.DataItem, "custFirstName" + ", " + DataBinder.Eval(Container.DataItem, "custID")%></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>


protected void EditCustomer(Object sender, EventArgs e)
{

}

How can I get the custID value in the EditCustomer event?

Answer

Tim Schmelter picture Tim Schmelter · Jul 24, 2012

Youc an pass the CustomerID as CommandArgument:

<asp:LinkButton OnClick="EditCustomer" id="lbtnCustomerName" 
     CommandArgument='<%#Eval("CustomerID")%>'
     CommandName="CustomerName"
     OnCommand="LinkButton_Command"
     Visible="true" runat="server"
     ToolTip="Click to edit customer."><%# DataBinder.Eval(Container.DataItem, "custLastName") + ", " + DataBinder.Eval(Container.DataItem, "custFirstName" + ", " + DataBinder.Eval(Container.DataItem, "custID")%>
</asp:LinkButton>

Now you can handle the LinkButton's Command event:

void LinkButton_Command(Object sender, CommandEventArgs e) 
{
   String CustomerID = e.CommandArgument.ToString();
}