当我在gridview中单击linkbutton时,如何获得行索引

lev*_*y92 3 c# asp.net gridview

我必须定位当我clik链接按钮获取行的索引.但是,我无法得到它.

我的c#代码:

 int rowIndex = Convert.ToInt32(e.CommandArgument);
Run Code Online (Sandbox Code Playgroud)

当代码到达这里时会出现错误({"输入字符串格式不正确."})但是,例如当我单击buttonfield时它会起作用.我该怎么做?

asp.net代码

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

Ari*_*ion 6

我会做这样的事情:

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>
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)