Get DataKey values in GridView RowCommand
Asked Answered
E

5

53

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.

Enlarger answered 12/5, 2010 at 11:13 Comment(0)
T
94

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"];
Tithe answered 12/5, 2010 at 12:33 Comment(5)
I ended up using the CommandArgument, but I can see how this solution would also work.Enlarger
When I used a link rather than a button, I got this to work without setting CommandArgument in the aspx page. The CommandArguement property of the event arg contained the index of the row. I just used the code for the server event and it worked.Spirochete
Vb Code: Dim rowIndex As Integer = Integer.Parse(e.CommandArgument.ToString()) Dim val As String = Me.grdDatosPadres.DataKeys(rowIndex).Item("Field").ToStringEmboly
I just want to add that you can get row index like this without adding it to command argument " ((GridViewRow)((LinkButton)e.CommandSource).Parent.Parent).RowIndex; " and use command argument for another data to be stored.Landmass
As an alternative, if you do prefer to specify a particular data item declaratively in the .aspx rather than "fishing" for it in code-behind, you can specify it like this in the .aspx: CommandArgument='<%# DataBinder.Eval(Container.DataItem, "cdbConsultantId") %>' and use it in code simply as e.CommandArgument (note that it is an object and you may need a cast depending on what you want to do with it). You may find this simpler and/or more clear in some situations.Gaynor
E
33

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;
    }
 }
Exclave answered 12/7, 2011 at 23:33 Comment(1)
when using multiple datakeys i suggest using : string ID = myGrid.DataKeys[myRow.RowIndex].Values("ID").ToString()Dishonor
C
12
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();
Colorant answered 14/10, 2014 at 9:39 Comment(0)
T
5

you can just do this:

string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
Tonguelash answered 8/8, 2012 at 17:15 Comment(1)
No, that's not enough. The initial value of CommandArgument is not the row ID, it's an empty string.Annalee
D
3

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument
Doubloon answered 22/7, 2015 at 11:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.