I have a GridView
with an associated DataKey
, which is the item ID.
How do I retrieve that value inside the RowCommand
event?
This seems to work, but I don't like the cast to LinkButton
(what if some other command is firing the event?), and I'm not too confident about the NamingContainer
bit.
LinkButton lb = (LinkButton)e.CommandSource;
GridViewRow gvr = (GridViewRow)lb.NamingContainer;
int id = (int)grid.DataKeys[gvr.RowIndex].Value;
I'm aware that I could instead pass that ID as the CommandArgument
, but I chose to use DataKey
to give me more flexibility.
I'm also aware that it's possible to use a hidden field for the ID, but I consider that a hack that I don't want to use.
I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.
On the Button:
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
On the Server Event
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];
I managed to get the value of the DataKeys using this code:
In the GridView I added:
DataKeyNames="ID" OnRowCommand="myRowCommand"
Then in my row command function:
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;
}
}
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();
you can just do this:
string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
On the Button:
CommandArgument='<%# Eval("myKey")%>'
On the Server Event
e.CommandArgument
来源:https://stackoverflow.com/questions/2818203/get-datakey-values-in-gridview-rowcommand