如何通过在 ASP.NET gridview 中单击一行中的按钮来获取行数据 [英] How to get row data by clicking a button in a row in an ASP.NET gridview

查看:23
本文介绍了如何通过在 ASP.NET gridview 中单击一行中的按钮来获取行数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.NET Web 应用程序中有一个 GridView,我在其中每行添加了两个按钮:

I have a GridView in a ASP.NET web application, in which I have added two buttons in each row:

 <ItemTemplate>
    <asp:Button ID="btnEdit" Text="Edit" runat="server" />
    <asp:Button ID="btnDelete" Text="Delete" runat="server"/>
 </ItemTemplate>

现在如何通过单击一行中的编辑按钮从 gridview 中获取行数据?

Now how I can get the row data from gridview simply by clicking an edit button in a row?

推荐答案

你也可以像这样使用按钮点击事件:

You can also use button click event like this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="Button1" runat="server" Text="Button" 
                    OnClick="MyButtonClick" />
    </ItemTemplate>
</asp:TemplateField>

protected void MyButtonClick(object sender, System.EventArgs e)
{
    //Get the button that raised the event
    Button btn = (Button)sender;

    //Get the row that contains this button
    GridViewRow gvr = (GridViewRow)btn.NamingContainer;
} 

你可以这样做来获取数据:

OR

You can do like this to get data:

 void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
 {

    // If multiple ButtonField column fields are used, use the
    // CommandName property to determine which button was clicked.
    if(e.CommandName=="Select")
    {
      // Convert the row index stored in the CommandArgument
      // property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);    

      // Get the last name of the selected author from the appropriate
      // cell in the GridView control.
      GridViewRow selectedRow = CustomersGridView.Rows[index];
    }
}

和 gridview 中的 Button 应该有这样的命令并处理 rowcommand 事件:

and Button in gridview should have command like this and handle rowcommand event:

<asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="CustomersGridView_RowCommand"
        runat="server">

        <columns>
          <asp:buttonfield buttontype="Button" 
            commandname="Select"
            headertext="Select Customer" 
            text="Select"/>
        </columns>
  </asp:gridview>

在 MSDN 上查看完整示例

这篇关于如何通过在 ASP.NET gridview 中单击一行中的按钮来获取行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆