- DataGridView Overview
- Basic Data Binding with the DataGridView
- Controlling Modifications to Data in the Grid
- Programmatic DataGridView Construction
- Custom Column Content with Unbound Columns
- Displaying Computed Data in Virtual Mode
- Using the Built-In Column Types
- Built-In Header Cells
- Handling Grid Data Edits
- Automatic Column Sizing
- Column and Row Freezing
- Using the Designer to Define Grids
- Column Reordering
- Defining Custom Column and Cell Types
- Utilizing Cell-Oriented Grid Features
- Formatting with Styles
- Where Are We?
Column and Row Freezing
Scrolling is inevitable when dealing with lots of rows or columns of data. Often when you scroll through data, it is easy to lose the context of what rows or columns you are looking at, especially if that context is based on the values in some other rows or columns. Let’s say you are browsing through a grid filled with product information. If there are a lot of columns of data associated with each product, as you scroll to the right to view columns that aren’t currently displayed, you will lose the context of the product name as it gets scrolled off the left of the screen. What you would really want in this situation is to be able to freeze the product name column so that it is always shown and only have the remaining columns scroll. Likewise, there may be situations where you need to present one or more rows at the top of the grid that need to remain in place as you scroll down to additional rows in the grid.
Accomplishing this with the DataGridView control is simple: You just set the Frozen property to true on any row or column to get this behavior. Specifically, if you freeze a column, then that column, and all the columns to the left of it, won’t scroll when you scroll to the right in the grid. Similarly, if you freeze a row, then that row and all the rows above it won’t scroll when you scroll down in the grid. If you are going to freeze a column or row, then you will probably want to provide a visual cue to the user indicating the logical boundary that exists between the frozen item and the nonfrozen ones next to it. The easiest way to do this is to set the DividerWidth property on the column or row to something other than the default. This property is an integer that specifies the number of pixels used to draw the divider between cells of that column or row and the adjacent one (to the right or below).
The following code shows a simple example of freezing both a column and a row and setting the divider width:
m_ProductsGrid.Columns["ProductName"].Frozen = true; m_ProductsGrid.Columns["ProductName"].DividerWidth = 3; m_ProductsGrid.Rows.Frozen = true; m_ProductsGrid.Rows.DividerHeight = 3;