在按钮单击时获取行的DataKeyNames

我有一个gridview,每行有按钮:

在此处输入图像描述

按钮位于模板字段中:

 ...         

如何在点击时获取数据密钥名称?

 protected void viewHoursButton_OnClick(object sender, EventArgs e) { //get PK_NonScrumStory for clicked row } 

我想到了:

 protected void viewHoursButton_OnClick(object sender, EventArgs e) { Button btn = sender as Button; GridViewRow row = btn.NamingContainer as GridViewRow; string pk = storyGridView.DataKeys[row.RowIndex].Values[0].ToString(); System.Diagnostics.Debug.WriteLine(pk); } 

您可以为自定义按钮绑定CommandNameCommandArgument ,例如:

  

然后你应该实现事件storyGridView1_RowCommand,并处理每个命令:

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DeleteItem") { // Retrieve the row index stored in the // CommandArgument property. int index = Convert.ToInt32(e.CommandArgument); // Retrieve the row that contains the button // from the Rows collection. GridViewRow row = GridView1.Rows[index]; //Retrieve the key of the row and delete the item } else if(e.CommandName == "EditItem") { //edit the item } //Other commands } 

你正在使用错误的事件。 使用

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

GridView.RowCommand – 它是网格上的事件,而不是单元格上的事件。 在单元格上,您提供CommandName string = so而不是OnClick事件,您将拥有CommandName =“ViewHours”。

然后在myGridView_RowCommand事件处理程序中,您将获得以下其中一个:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewcommandeventargs.aspx

并在e.CommandName上输入一个大的switch语句。 丑陋,但它的工作原理。

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

这会得到你的行索引。 您可以将它与myGridView.DataKeys [index]一起使用来获取DataKeys。

是的,我知道。