Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Built-In Header Cells

Header cells are the cells rendered at the top and left sides of the grid. They provide the context or a guide to what the cells in the grid contain. Column header cells are of type DataGridViewColumnHeaderCell, and their header text indicates the content of the column cells. The cell contains an up or down triangle when the column supports sorting; users can sort the column by clicking on the column header. Usually the header text is set through the HeaderText property on the column, either explicitly through code or implicitly through data binding based on the data’s schema. You can also access the header cell directly from the column through the HeaderCell property and use its Value to set the text displayed.

The row header cells are of type DataGridViewRowHeaderCell. They indicate row selections with a triangle glyph, editing mode with a pencil glyph, and the new row with a star glyph. Row header cells can display text as well; you set the cell’s Value to a string value by accessing the row’s HeaderCell property.

Both column and row headers can be further customized by implementing custom painting by handling the CellPainting event on the grid. Note that if you do custom painting, you must do all the painting of the header cell yourself, and then set the Handled property on the event argument to true:

private void OnCellPainting(object sender,
   DataGridViewCellPaintingEventArgs e)
{
   if (e.ColumnIndex < 0)
   {

      e.Graphics.FillRectangle(Brushes.Aqua, e.CellBounds);
      e.Handled = true;
   }
}

This code checks to see if the column being painted has an index less than zero, which indicates that the row header is being painted. The column index of the row headers is –1, and the row index of the column headers is also –1. You cannot index into the Cells collection on the row with these values, but you can use them as a flag in the CellPainting event to know when it is a header that is being painted.

Additionally, you can set the CellHeader property to an instance of a class that derives from DataGridViewCell, and then that cell type will be used when the header cells are rendered. You can derive your own class from the cell base class and do whatever kind of custom painting, formatting, or setting of styles there that makes sense.

  • + Share This
  • 🔖 Save To Your Account