Multiple DataKeyNames in GridView

I like GridView, but using it is a sometimes like getting behind the wheel of a 747 without ever flying before.

I have a software tracking report to make that pulls data out of database using an SQLDataSource. Everything in the database is keyed on the computer name, so to make a list of installed applications across the domain, I do a GROUP BY on application name and version in the select statement. The report displays the name, version, and count in a GridView. To get the list of computers where a particular application name and version instance is installed, I query the database on GridView select. But since it’s a GROUP BY, there is no permanent primary key, and so I need to know both the application name and the version for the query.

To get this information in the select handler I thought I’d use
1. gdvApplications.SelectedRow[”name”]
2. gdvApplications.SelectedRow[”version”]

but it turns out there are no indexers defined on the SelectedRow. Then I read about DataKeyNames. You can set this property of the GridView to the name(s) of one or more (comma separated) of your columns, and then something will show up in the SelectedValue property. In fact, this is supposed to be used to get PrimeryKey values out of a selected row.

gdvApplications.DataKeyNames = “name,version”; // In Page_Init() or correspondingly//in the aspx/ascx file.(…)

gdvApplications. SelectedValue[”name”];

gdvApplications.SelectedValue[”version”];

Except, er, well, no. There are no indexers defined on SelectedValue either. In fact it is just an object and corresponds only to the first column that is defined in DataKeyNames. To cut to the chase, if you have multiple DataKeyNames defined, here is how you can access them:

gdvApplications.DataKeys[gdvApplications.SelectedIndex].Values[”name”];

gdvApplications.DataKeys[gdvApplications.SelectedIndex].Values[”version”];

And yet it looks so simple in Visual Studio, you just drag and drop the GridView on your web form like a text box and follow the wizards. I’m glad that it can be done, but why wouldn’t we just have row indexers? I’d write a Code Project article on this, but I’ve let my membership in the National Association of Sarcastics lapse. (Like they need the money.) Anyway, this is really more of a case of “I let the IDE lead me by the nose (and it led me into a brick wall.)”

No comments: