我有一个具有关联DataKey
的GridView
,它是项ID。如何在RowCommand
事件中检索该值?
这似乎是可行的,但是我不喜欢强制转换为LinkButton
(如果其他命令触发了事件呢?),而且我对NamingContainer
部分也不是很有信心。
LinkButton lb = (LinkButton)e.CommandSource;
GridViewRow gvr = (GridViewRow)lb.NamingContainer;
int id = (int)grid.DataKeys[gvr.RowIndex].Value;
我知道我可以将该ID作为CommandArgument
传递,但我选择使用DataKey
来给我更大的灵活性。
我也意识到可以使用隐藏字段作为ID,但我认为这是一个我不想使用的技巧。
发布于 2010-05-12 20:33:25
我通常通过CommandArgument传递RowIndex,并使用它来检索我想要的DataKey值。
在按钮上:
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
在服务器事件上
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];
发布于 2011-07-13 07:33:00
我设法使用以下代码获得了DataKeys的值:
在GridView中,我添加了:
DataKeyNames="ID" OnRowCommand="myRowCommand"
然后在我的行命令函数中:
protected void myRowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton lnkBtn = (LinkButton)e.CommandSource; // the button
GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent; // the row
GridView myGrid = (GridView)sender; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey
switch (e.CommandName)
{
case "cmd1":
// do something using the ID
break;
case "cmd2":
// do something else using the ID
break;
}
}
发布于 2014-10-14 17:39:22
foreach (GridViewRow gvr in gvMyGridView.Rows)
{
string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}
您可以在使用foreach
进行迭代时或针对任何GridView事件(如OnRowDataBound
)使用此代码。
在这里,您可以通过逗号,
分隔,为DataKeyNames
输入多个值。例如,DataKeyNames="ProductID,ItemID,OrderID"
。
现在,您可以通过提供索引来访问每个DataKeys
,如下所示:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();
您也可以使用键名而不是它的索引从DataKeyNames
集合中获取值,如下所示:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();
https://stackoverflow.com/questions/2818203
复制相似问题