.NET Tips and Tricks

Blog archive

Working with Objects with the Window Form DataGridView

If you're using the Windows Forms DataGridView and loading data into columns by pulling that data out of properties on objects, you should know that there's an easier way. Just create a List of your objects and use that List to set the DataGridView's DataSource property. The DataGridView will generate a row for each object in the collection and column for each property on the class. Typical code would look like this:

Me.DataGridView1.DataSource = ListOfObjects

Of course, the objects you're putting in the DataGridView may have properties you don't want to display. You'll also want to control the left-to-right order that the properties are displayed in. To take control of the DataGridView's columns, select the Columns property in the Properties window and click on the builder button that appears (that's the button with the three little dots). That will bring up the Edit Columns dialog, where you can add columns to the grid and decide which property each column will display.

In code, you'll also need to set the AutoGenerateColumns property to false to prevent the DataGridView from adding all of your object's properties to the grid anyway:

Me.DataGridView1.AutoGenerateColumns = False

Generating the rows in the DataGridView from a list of objects also makes it easy to retrieve the object associated with each row. You don't pull the data from a row's columns and use those values to recreate the object; instead, you can just pull the object from the row's DataBoundItem property. This code processes all the objects for the rows that the user selected:

For Each row As DataGridViewRow In DataGridView.SelectedRows
  Dim obj As MyObject = CType(row.DataBoundItem, MyObject)
  '…process MyObject
Next

Posted by Peter Vogel on 09/03/2013


comments powered by Disqus

Featured

Subscribe on YouTube