我有一个每行按钮的gridview:
按钮位于模板字段中:
<asp:GridView ID="storyGridView" runat="server" AllowSorting="True" AutoGenerateColumns="False"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" DataKeyNames="PK_NonScrumStory" DataSourceID="SqlDataSource1">
...
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="viewHoursButton" runat="server" Text="View Hours" OnClick="viewHoursButton_OnClick" />
<asp:Button ID="addHoursButton" runat="server" Text="Add Hours" OnClick="addHoursButton_OnClick" />
<asp:Button ID="editButton" runat="server" Text="Edit" OnClick="editButton_OnClick" />
<asp:Button ID="deleteButton" runat="server" Text="Delete" OnClick="deleteButton_OnClick" />
</ItemTemplate>
</asp:TemplateField>
如何在点击时获取数据密钥名称?
protected void viewHoursButton_OnClick(object sender, EventArgs e)
{
//get PK_NonScrumStory for clicked row
}
答案 0 :(得分:8)
我明白了:
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);
}
答案 1 :(得分:5)
您可以为自定义按钮绑定CommandName
和CommandArgument
,例如:
<asp:Button ID="deleteButton"
runat="server"
Text="Delete"
CommandName="DeleteItem"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
OnClick="deleteButton_OnClick" />
然后你应该实现事件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
}
答案 2 :(得分:3)
你正在使用错误的事件。使用
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。
...
是的,我知道。