NDP - ADO.NET 2.0
DGV styles

Style includes:

Plus, you can change the formatting of values within the cells.

The display style of a cell is computed by working up from default styles at several levels.

For example:

DataGridViewCellStyle class

Each cell computes an InheritedStyle. For a non-header cell, the properties used to compute a cell's style are:

 

In the project DGV\Style, we have set a few of these things. All but the first, you will find by poking around. The DataGridViewColumn.DefaultCellStyle is set on the LastName column.

Have fun with the Style Editor.

There is also code to do custom formatting and parsing on the Age column. First, I changed the name on the column to be "Age". Then I added handlers for the CellFormatting and CellParsing events.

The CellFormatting event occurs when the grid is getting ready to display a cell. You can set the Format property on cell style to get some standardized formatting. Here, I wanted to take the age and add some junk characters, and also to color code.

The problem if the user edits is that those junk characters might still be there. So, we capture the CellParsing event which converts the actual value in the cell into the underlying data value. This occurs when EndEdit is called or the user tries to navigate away from the cell. In this code, we get rid of all non-digits and then convert.

       private void studentDataGridView_CellFormatting(object sender, 
                               DataGridViewCellFormattingEventArgs e)
        {

            if (studentDataGridView.Columns[e.ColumnIndex].Name == "Age")
            {
                if (e.Value == null)
                    return;

                int age = (int)e.Value;
                e.CellStyle.BackColor = (age > 60 ? Color.AliceBlue 
                                         : age > 30 ? Color.Bisque 
                                         : Color.Coral);
                e.Value = ">>> " + e.Value + " <<<";
                e.FormattingApplied = true;
            }
        }

        private void studentDataGridView_CellParsing(object sender, 
                                DataGridViewCellParsingEventArgs e)
        {
            if (studentDataGridView.Columns[e.ColumnIndex].Name == "Age")
            {
                if (e.Value != null)
                {
                    string value = e.Value.ToString();
                    string hacked = Regex.Replace(value, @"\D", "");
                    try
                    {
                        int age = Convert.ToInt32(hacked);
                        e.Value = age;
                        e.ParsingApplied = true;
                    }
                    catch (FormatException)
                    {
                    }
                    catch (OverflowException)
                    {
                    }
                }
            }
  
        }