Getting the DataKey of a GridView bound inside a DataList

You know you nest your GridViews inside your DataLists. Everybody is doing it, and peer pressure is something you are going to give in to. I know that when my friends started doing it, I couldn’t resist. But once you start doing that sort of thing, then you have to do things like get your DataKey values from nested GridView, and that is no longer as simple as it used to be.

First, a bit of HTML to show exactly what I’m doing, with the standard disclaimer that I took a bunch of “highly relevant to me but not to thee” items:

     <asp:DataList ID="lstTest" DataKeyField="ID" DataSourceID="OC" OnItemCommand="lstTest_ItemCommand" runat="server">
            <asp:Panel ID="pnlPanel" runat="server">
                <asp:Label ID="lblLocationName" Text='<%#Eval("Name")%>' runat="server" />
                <asp:Label ID="lblLocOwner" Text='<%#Eval("OwnerName")%>' runat="server" />
                <asp:GridView ID="grdDetails" OnRowCommand="grdDetails_OnCommand" DataKeyNames="ID"  runat="server">
                        <asp:BoundField DataField="UserName"  />
                        <asp:ButtonField CommandName="IgnoreRequest" Text="Ignore Request" />
                        <asp:ButtonField CommandName="IgnoreUser" Text="Ignore User" />

 So each item in the DataList has its own GridView assigned to it. Beautiful. But when I click on the Ignore button inside the DataGrid, I can’t just say grdDetails.DataKeys[grdDetails.SelectedIndex].Value. Why? Because grdDetails doesn’t exist at the page level, only in the ItemTemplate of the DataList. Thus, type grdDetails. and expecting your methods, properties, and events goodness will bring bitter tears to your face. But not for long.

 Let’s do some .NET-foo on it:

     protected void grdDetails_OnCommand(object sender, GridViewCommandEventArgs e)
        GridView gv = (GridView)sender;
        int Index = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName == "IgnoreRequest")

So I’m first casting the sender as a GridView, because that’s what the sender is. Since the GridViewCommandEventArgs .CommandArgument is actually the index of the GridView row (it’s tricky like that), I can then use that index an pull the value from the GridView’s DataKeys collection. Bingo boingo done.

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: