DataGridView Columns, Edit Columns Dialog

Dot Net Perls

You are trying to figure out how the Edit Columns dialog in Visual Studio works with the DataGridView control. Find out how columns work in the DataGridView and how you can configure the control in Windows Forms to display columns properly. Here we look at the Edit Columns dialog for DataGridView and review ways you can add columns, change what database fields they display, and what their headers are displayed as.

DataGridView columns dialog

Add columns

First, after you create your DataGridView in Visual Studio by dragging it to your Windows Form, you will want to configure the columns to display data correctly. With the DataGridView, you can predefine columns for display. This doesn't actually display anything, but you create the rules by which the actual data will be displayed.

Steps to get started. This is ideal for when you want to have the first column have a width of 200px, for example. For the tutorial, we want one of the DataGridView's columns to be 110px wide.

Steps

Step 1. Go to Properties > Misc > Columns. This shows the Edit Columns dialog box. Click on the Add... button the bottom left. A screenshot is shown at top of this article.

Step 2. Change the Unbound column. An Unbound column is one that is not directly linked to a DataSource. Note that sometimes it is easier to use the DataSource directly.

Step 3. Change the header text. The text you type into the Header text: text box will ensure that the text is always shown. This means you can display a different form of the column's name than is in the actual DataTable and database.

Step 4. Finally, change the properties. You need to change the properties of the DataGridViewColumn in the dialog box that appears. I set 110px as the width, and AutoSizeMode of None.

Change DataPropertyName

You need to specify that a certain column in your database be inserted into the Column you just added in the Columns dialog box. To do this, you must assign the DataPropertyName of the column to the column name from your database.

For example, to specify that your DataGridViewColumn be used for the Weight column for your database, type "Weight" into the DataPropertyName box.

Column properties

Property (Icon copyright Microsoft)

There are many more columns on the DataGridView control that you will want to adjust. The collection of properties available is in the DataGridView Property article at this site.

DataGridView Property Notes

Summary

We looked at how the Edit Columns and Add Columns dialog work when trying to configure DataGridView controls correctly. The columns are used as a template for how your DataGridView will deal with the data you assign through its DataSource. This is not entirely intuitive, but once you figure it out it is very useful.

DataGridView Tutorial Windows Forms