.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

  • See Prompts Microsoft Engineers Use for Bleeding-Edge Multimodal RAG AI Research

    Vision-centric queries show how front-line experts are prompting LLMs these days.

  • AI Explains Expressions in Update to Java on VS Code

    "The Spring Tools now show code lenses above these expressions that allow you to quickly let GitHub Copilot explain those statements for you."

  • Microsoft Eases Integration with Semantic Kernel AI SDK

    The basic idea is to provide unified API abstractions, especially for idiomatic C# code, to help platform developers and others work with any provider with standard implementations for caching, telemetry, tool calling and other common tasks.

  • Final .NET 9 Preview Ships with Go-Live License

    Visual Studio developers can now download the SDK for .NET 9 Release Candidate 2 with a go-live license, meaning devs get Microsoft support for production applications even before the framework reaches general availability next month.

Subscribe on YouTube