Share via


DataGridView

Click here for larger image

The DataGridView control is a new Windows Forms 2.0 control that replaces the DataGrid control. This control is easier to use and much more powerful than the DataGrid.

At design time, you can easily set the DataGridView’s data source property. This will add a column to the grid for every column in the data source. You can also manage columns (add/remove) by using the Edit Columns dialog.

The DataGridView comes with TextBox, Image, CheckBox, ComboBox, Link, and Button column and cell types. Addition cell or column types can be easily implemented to extend your application. Columns and rows both support heterogeneous cell types. For example, you can have column of check box cells and have other cell types, like a button, in the same column.

The DataGridView supports multiple data sources. You can data bind to a data source such as a SQL server, or you can be unbound and manually add/remove rows. You can also use a virtual mode that provides the ability to virtually have 100,000+ rows! The DataGridView even supports a mix of data bound columns and virtual columns.

Styles can be used to format the grid. Styles can be specified for individual cells, rows, columns or for the whole table. Styles are also inherited, so if you set the BackColor to blue for the table and set a custom font for a cell, the cell will be shown with a blue background and custom font.

Cells in the grid are almost as powerful as a standard control – events that you would expect to find on a control are on a cell. Events like MouseEnter and MouseDown can be used to perform custom cell actions. These events are bubbled to the DataGridView control via the CellMouseEnter and CellMouseDown events, respectively.

Individual cells can be formatted easily by setting a cell property like Style, but the CellFormatting event is the best place to format the cell’s value or style based upon its value. For example, you can format a cell’s BackColor to be Red if its value is negative. You can also perform custom cell and row painting to create really custom styles. You can handle the CellPainting or RowPrePaint/RowPostPaint events to perform custom painting.