Title: Format DataGridView columns in C#
This example shows how you can format DataGridView columns to make them display values properly. The control is actually pretty smart and will usually do the right thing if you give it the right data. For example, if a column contains numeric data, it will sort that column numerically rather than textually. For example, 2 comes before 12 numerically but 12 comes before 2 when treated as text.
The most important step is feeding the control the right data types. If a column should hold a numeric value, pass the control numeric data. For example, the following statement adds a new row to this example's DataGridView control.
dgvValues.Rows.Add("Notebook", 1.17m, 6m, 1.17m * 6m);
The second, third, and fourth data values are numeric so the control automatically sorts them numerically.
You can also customize the way the control displays its data. To do that, select the control in the Form Designer, click the smart tag (the little triangle) in its upper right corner, and select Edit Columns. IN the Edit Columns dialog shown on the right, you can set the column's name, header text, width, column type (which can be button, checkbox, combobox, image, link, or textbox), and other properties.
To set the column's formatting, click the DefaultCellType entry and click the ellipsis on the right to see the dialog shown on the right. Here you can set several useful properties. For example, you can:
- Use the Alignment property to right-align numeric values
- Set Format to C2 for currency with two digits after the decimal place or N0 for numbers with no digits after the decimal place
- Set NullValue to the value you want the control to display if a data value in the column is null
In summary, the DataGridView control is quite powerful, if you give it the right kinds of data and a few hints about column formatting.
Download the example to experiment with it and to see additional details.