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; } }
The CalculateTotals 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.
Comments