.NET Tips and Tricks

Blog archive

Simplifying Data Retrieval in the GridView

Retrieving data from the GridView can involve passing integer values to the GridView's Rows and Cells properties—resulting in code that's not only hard to read but brittle: it will break as soon as you add, remove, or reorder the columns in the GridView. But there's an easy way to pull out data if you use the GridView's SelectedValue property. You've probably used the SelectedValue property with a listing control (e.g. the DropDownList, the RadioButtonList).

The issue with SelectedValue is that it returns a single value. That's not an issue with a listing control because each item has only one value. With a GridView, however, the user selects a whole row; so typically, there are multiple values returned. To take advantage of the GridView's SelectedValue property, you need to set the GridView's DataKeyNames property to specify which field will have its value returned in the SelectedValue property.

The DataKeyNames property accepts a string of comma-delimited field names (presumably, the field(s) that make up the primary key for the rows displayed in the GridView). The DataKeyNames property performs multiple functions, but as far as SelectedValue is concerned, it's the first field you specify in DataKeyNames that matters: that field's value turns up in the SelectedValue property when the user selects a row in the GridView. So, if there's some column that you typically need to retrieve from the GridView, make sure that that's column's field is the first one in the list in the DataKeyNames list. Once you've done that, you can pull that field's value from the SelectedValue property when the user selects a row (I've assumed that you've enabled selection from the GridView's smart tag).

When using the SelectedValue property, you should always check that a row's been selected before attempting to use the property. Typical code for working with SelectedValue looks like this:

  Dim res As Object
If Me.CustomerGrid.SelectedRow IsNot Nothing Then
res = Me.CustomerGrid.SelectedValue
End If

If you need more than just one value, you can use the GridView's SelectedDataKey property. The Values property on the SelectedDataKey, for instance, returns a Dictionary of all the fields you specified in the DataKeyNames property. You can retrieve the values of any of those fields by position or by name (as this example does):

res = Me.CustomerGrid.SelectedDataKey.Values.Item("CustomerID")

Posted by Peter Vogel on 09/09/2011 at 1:16 PM


comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.