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

时间:2012-04-07 11:44:11

标签: c# asp.net gridview

当我按下链接按钮获取行索引时,我必须定位。但是,我无法得到它。

我的c#代码:

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

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

asp.net代码

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

2 个答案:

答案 0 :(得分: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>

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

}

答案 1 :(得分:2)

请使用以下内容:

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

我的意思是,添加一个CommandArgument。