Calculate a column total in the DataGridView and
display in a textbox
A common requirement is to calculate
the total of a currency field and display it in a textbox. In the snippet
below, we will be calculating the total of the ‘Freight’ field. We will then
display the data in a textbox by formatting the result (observe the ToString("c")) while displaying the data, which
displays the culture-specific currency.
C#
private void btnTotal_Click(object
sender, EventArgs e)
{
if(dgv.Rows.Count > 0)
txtTotal.Text = Total().ToString("c");
}
private double
Total()
{
double tot = 0;
int i = 0;
for (i = 0; i < dgv.Rows.Count; i++)
{
tot = tot + Convert.ToDouble(dgv.Rows[i].Cells["Freight"].Value);
}
return tot;
}
No comments:
Post a Comment