Set DataGridView column styles in C#


You can set DataGridView column styles by setting a column’s DefaultCellStyle property. It determines the column’s appearance including its foreground color, background color, font, alignment, and colors to use when an item is selected.

To set a column’s style at design time, select the control, click the Columns property in the Properties window, and click the ellipsis to the right. In the Column Editor, select a column, click the DefaultCellStyle property, and click the ellipsis to the right. Finally, in the CellStyle Builder, set the properties that you want to use. In this example, I set the first column’s style at design time.

To set a column’s style at run time, create a DataGridViewCellStyle object, set its properties, and assign it to a column’s DefaultCellStyle property as in the following code.

// Define a column style at run time.
DataGridViewCellStyle cell_style = new DataGridViewCellStyle();
cell_style.BackColor = Color.LightGreen;
cell_style.Alignment = DataGridViewContentAlignment.MiddleRight;
cell_style.Format = "C2";
dgvValues.Columns[3].DefaultCellStyle = cell_style;

Note that the DataGridView control initially sets column styles that more or less make sense. For example, if a column contains integer data, it aligns that column on the right. If a column contains decimal data, it displays the values in that column as currency. If you set DataGridView column styles of your own, then you should probably use similar settings.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in controls, user interface and tagged , , , , , , , , , , , . Bookmark the permalink.

1 Response to Set DataGridView column styles in C#

  1. kellor says:

    Customize GridView Style in C#

    [Editor’s note: This link leads to a DataGridView WinForms Component that you can buy to make more customizable data grid view controls. It’s related to this post so I’m leaving it, but I haven’t tried it out so I don’t know how good it is.]

Comments are closed.