How can i get the row index when i click the linkbutton in gridview

I need to target when I click a link button to get the row index. However, I don't understand.

My C # codes:

 int rowIndex = Convert.ToInt32(e.CommandArgument);

      

when the codes come here gives an error ({"The input line was not in the correct format."}) however it works, for example when I press a button. How can i do this?

asp.net codes

  <asp:TemplateField>
           <ItemTemplate>
               <asp:LinkButton ID="LinkButton2" runat="server" CommandName="View"><%#Eval("RSS_Title") %></asp:LinkButton>
           </ItemTemplate>

      

+3


source to share


2 answers


I would do it something like this:

ASPX

<asp:GridView ID="YourGrid" 
              OnRowCommand="YourGrid_RowCommand"
              OnRowCreated="YourGrid_RowCreated"  
              runat="server">
  <Columns>
    <asp:TemplateField>
       <ItemTemplate>
           <asp:LinkButton ID="LinkButton2" runat="server" CommandName="View">
           <%#Eval("RSS_Title") %></asp:LinkButton>
       </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

      



CS

protected void YourGrid_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName=="View")
    {
      int index = Convert.ToInt32(e.CommandArgument);
    }
}
protected void YourGrid_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      var LinkButton2 = (LinkButton)e.Row.FindControl("LinkButton2");
      LinkButton2.CommandArgument = e.Row.RowIndex.ToString();
    }

}

      

+6


source


Please use the following:

<asp:LinkButton ID="LinkButton2" runat="server" CommandName="View" CommandArgument="1"><%#Eval("RSS_Title") %></asp:LinkButton>

      



I mean add CommandArgument.

+2


source







All Articles