GridView里面每一行都一个button按钮,当我点击按钮的时候,如何知道我点击的是Gridview第几行?
 protected void GridPro_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button btn = (Button)e.Row.Cells[7].FindControl("fenjiebtn");            string productname = e.Row.Cells[0].Text.ToString();
            string productalias = e.Row.Cells[1].Text.ToString();
            string qty = e.Row.Cells[4].Text.ToString();
          
            btn.Attributes.Add("onclick", "productchaifen('" + productname + "','" + productalias + "','" + qty + "')");
        }    }按钮的事件是调用productchaifen脚本做相关操作的。

解决方案 »

  1.   

    事件
     _RowCommand(object sender, GridViewCommandEventArgs e)
    行号
    int index = Convert.ToInt32(e.CommandArgument);
      

  2.   

                     <asp:LinkButton   ID="lbUse" runat="server" OnClick="lbUse_Click" CommandName="Use" CommandArgument='<%#Eval("id") %>'> 使用此模板</asp:LinkButton>
    放在gridview模板里面protected void GridPro_RowDataBound(object sender, GridViewRowEventArgs e) 
        { 
            if (e.Row.RowType == DataControlRowType.DataRow) 
            { 
                Button btn = (Button)e.Row.Cells[7].FindControl("fenjiebtn"); 
                btn.Attributes.Add("onclick", "<script>"+((LinkButton)sender).CommandArgument.ToString()+"<script>"); 
            }     } 
      

  3.   

    想得简单点。给GridView增加一个ButtonField, CommandName改成随便什么(不要Update/Insert/New/Delete/Select这几个)。
    如:
    <asp:ButtonField ButtonType="Button" CommandName="Damn" Text="按钮" />
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       if(e.CommandName == "Damn")
                Response.Write(e.CommandArgument);
    }
      

  4.   

    把刚才增加的ButtonField转换成TemplateField,这回点了没反应。那就增加红色部分。<asp:TemplateField ShowHeader="False">
       <ItemTemplate>
            <asp:Button ID="Button1" runat="server" CausesValidation="false" 
                                CommandName="Damn" Text="按钮" CommandArgument='<%# Container.DisplayIndex %>' />
       </ItemTemplate>
    </asp:TemplateField>
      

  5.   

    有个问题就是Container.DisplayIndex能不能传Container.DataItemIndex。改一下RowCommand,也就是通过GridView的行索引取得DataKeys,也就是数据库表里对应的主关键字字段。
    记得启用分页。protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       if(e.CommandName == "Damn")
         Response.Write(GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString());
    }第一页点击Button时没问题。第二页开始就出现"索引超出范围。必须为非负值并小于集合大小。"的错误。所以必须传Container.DisplayIndex。