Set a DataGridView control's column styles in C#

You can set a DataGridView column's DefaultCellStyle property to a style that 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 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 make your own column styles, then you need to use similar settings if you want them.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.