如何在ASP.NET GridView中点击按钮获取一行数据

25

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

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

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

7个回答

52

您也可以使用以下方式来处理按钮点击事件:

<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

您可以像这样获得数据:

 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中,每个按钮都应该有类似以下的命令,并处理RowCommand事件:

<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 上查看完整示例


谢谢您的快速回复。我已经尝试了那个方法,但是出现了以下错误:“无效的回发或回调参数。在配置文件中启用了事件验证,使用<页面enableEventValidation="true"/>或在页面中使用<%@ Page EnableEventValidation="true" %>。出于安全考虑,此功能验证回发或回调事件的参数是否来自最初呈现它们的服务器控件。如果数据有效且符合预期,请使用ClientScriptManager.RegisterForEventValidation方法注册回发或回调数据以进行验证。” - Tamal Kanti Dey
@TamalKantiDey - 嘿,只需设置EnableEventValidation="false",就可以消除那个错误。 - Pranay Rana
在页面顶部的标签 "<%@ Page" 中。 - Pranay Rana
谢谢,它正在工作,我的意思是没有错误出现。但是_RowCommand事件没有触发。 - Tamal Kanti Dey
@TamalKantiDey,你应该只在第一次页面加载时绑定GridView。 - sp_m
显示剩余4条评论

3

commandName放置在.aspx页面中

 <asp:Button  ID="btnDelete" Text="Delete" runat="server" CssClass="CoolButtons" CommandName="DeleteData"/>

订阅网格的 rowCommand 事件,你可以像这样尝试:

protected void grdBillingdata_RowCommand(object sender, GridViewCommandEventArgs e)
{
        if (e.CommandName == "DeleteData")
        {
            GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
            HiddenField hdnDataId = (HiddenField)row.FindControl("hdnDataId");
         }
}

这不错,只是你忘记了包括 hdnDataId 来自哪里。 - NetMage

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

你的方法
 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;
}

2
这似乎与Pranay Rana的答案完全相同。 - brz

1

您是否有特定的原因想要在项模板中放置按钮。您也可以通过以下方式完成,从而为您提供完整的网格行编辑事件控制权。您还可以轻松地连接取消和删除功能。

标记

<asp:TemplateField HeaderText="Edit">
            <ItemTemplate>
   <asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
    ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit" 
    CausesValidation="False"  />

      </ItemTemplate>

         <EditItemTemplate>

                    <asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update" 
                        Text="Update"  Visible="true" ImageUrl="~/images/saveHS.png" 
                        />
                   <asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"   
                        ImageUrl="~/images/Edit_UndoHS.png"  />

                 <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"   
                        ImageUrl="~/images/delete.png"  />

             </EditItemTemplate>


        <ControlStyle BackColor="Transparent" BorderStyle="None" />
               <FooterStyle HorizontalAlign="Center" />
           <ItemStyle HorizontalAlign="Center" />
       </asp:TemplateField>

代码后台

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataBind();

TextBox txtledName =   (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");

 //then do something with the retrieved textbox's text.

}

1
<asp:TemplateField>
   <ItemTemplate>
  <asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click"   > 
 </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>

  protected void LnKB_Click(object sender, System.EventArgs e)
  {
        LinkButton lb = sender as LinkButton;

        GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
        int x = clickedRow.RowIndex;
        int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
        lbl.Text = yourgridviewname.Rows[x].Cells[2].Text; 
   }

0
            <asp:Button  ID="btnEdit" Text="Edit" runat="server"  OnClick="btnEdit_Click" CssClass="CoolButtons"/>


protected void btnEdit_Click(object sender, EventArgs e)
{
       Button btnEdit = (Button)sender;
       GridViewRow Grow = (GridViewRow)btnEdit.NamingContainer;
      TextBox txtledName = (TextBox)Grow.FindControl("txtAccountName");
      HyperLink HplnkDr = (HyperLink)Grow.FindControl("HplnkDr");
      TextBox txtnarration = (TextBox)Grow.FindControl("txtnarration");
     //Get the gridview Row Details
}

同样适用于删除按钮


0
 protected void btnS10_click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in Grd.Rows)
        {
            CheckBox chk_Single = (CheckBox)row.FindControl("ChkSendOne");
            if (row.RowType == DataControlRowType.DataRow)
            {
                string id = (row.Cells[0].FindControl("lblSNo") as Label).Text;
                if (Convert.ToInt32(id) <= 10)
                {
                   
                    chk_Single.Checked = true;
                    if (chk_Single.Checked == true)
                    {
                        lblSelectedRecord.InnerText = (Convert.ToInt32(lblSelectedRecord.InnerText) + 1).ToString();
                    }
                }
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接