leventkalay92
leventkalay92

Reputation: 585

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

I have to target when i clik the link button get the index of row. However, Icannot get it.

My c# codes:

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

when the codes comes here gives error({"Input string was not in a correct format."}) however, it works for example when i click buttonfield. how can i do it?

asp.net codes

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

Upvotes: 3

Views: 13293

Answers (2)

Arion
Arion

Reputation: 31249

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();
    }

}

Upvotes: 6

sarwar026
sarwar026

Reputation: 3821

Please use the following:

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

I mean, add a CommandArgument.

Upvotes: 2

Related Questions