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();