[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 * (int)row.Cells["Quantity"].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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.