foreach (GridViewRow gvr in gvMyGridView.Rows)
{
string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}
You can use this code while doing an iteration with foreach
or for any GridView event like OnRowDataBound
.
Here you can input multiple values for DataKeyNames
by separating with comma ,
. For example, DataKeyNames="ProductID,ItemID,OrderID"
.
You can now access each of DataKeys
by providing its index like below:
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();
You can also use Key Name instead of its index to get the values from DataKeyNames
collection like below:
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();