Calculate and highlight DataGridView values in C#

Calculate and highlight DataGridView values

This example shows how to calculate and highlight DataGridView values at run time. It uses the following code to initialize its DataGridView control. It sets each item’s description, unit price, and quantity, but not its total cost.

// Make some data items.
dgvValues.Rows.Add(new object[] { "Pencils, dozen", 1.24m, 4 });
dgvValues.Rows.Add(new object[] { "Paper, ream", 3.75m, 3 });
dgvValues.Rows.Add(new object[] { "Cookies, box", 2.17m, 12 });
dgvValues.Rows.Add(new object[] { "Notebook", 1.95m, 2 });
dgvValues.Rows.Add(new object[] { "Pencil sharpener", 12.95m, 1 });
dgvValues.Rows.Add(new object[] { "Paper clips, 100", 0.75m, 1 });

The code then calls the following CalculateTotals method to calculate the items’ total costs.

// Calculate the total costs and
// highlight totals greater than $9.99.
private void CalculateTotals()
    // Make a style for values greater than $9.99.
    DataGridViewCellStyle highlight_style =
        new DataGridViewCellStyle();
    highlight_style.ForeColor = Color.Red;
    highlight_style.BackColor = Color.Yellow;
    highlight_style.Font =
        new Font(dgvValues.Font, FontStyle.Bold);

    // Calculate the total costs.
    foreach (DataGridViewRow row in dgvValues.Rows)
        // Calculate total cost.
        decimal total_cost =
            (decimal)row.Cells["PriceEach"].Value *

        // Display the value.
        row.Cells["Total"].Value = total_cost;

        // Highlight the cell if the vcalue is big.
        if (total_cost > 9.99m)
            row.Cells["Total"].Style = highlight_style;

This method creates a DataGridViewCellStyle that it will use to highlight cells with large total costs. It then loops through the rows setting each row’s Total entry.

Notice that the code uses the names of the columns as indexes. The column names were set at design time when I defined the columns. The code could use the column indexes, but this is easier to read and will still work if you rearrange the columns.

If a column’s calculated total is greater than $9.99, the code sets the total cell’s Style to the highlight style.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in controls, user interface and tagged , , , , , , , , , . Bookmark the permalink.

One Response to Calculate and highlight DataGridView values in C#

  1. Reading good blogs enable me to connect to other people and learn something new about their experiences. Thanks for posting this.

Leave a Reply

Your email address will not be published. Required fields are marked *