[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Set DataGridView column styles in C#

example

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.