如何通过单击ASP.NET网格视图中的行中的按钮来获取行数据

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

      

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

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

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

要么

您可以这样做以获取数据:

  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事件:

      

检查MSDN上的完整示例

commandName放在.aspx页面中

   

为网格订阅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"); } } 

你有什么特别的理由想要你的按钮在一个项目模板。你可以通过以下方式做到这一点,通过给你网格行编辑事件的全部function。你也可以轻松获得取消和删除function。

标记

              

代码背后

  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. } 
    

和你的方法

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

和删除按钮相同