I have type the value in GridView column.
After enter some data into the GridView, I want it to calculate the sum of one particular column.
How can I achieve this?
I have type the value in GridView column.
After enter some data into the GridView, I want it to calculate the sum of one particular column.
How can I achieve this?
If what you need is to display the sum of a particular column in a dataGridView, then this could help:
private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 5)
textBox9.Text = CellSum().ToString();
}
private double CellSum()
{
double sum = 0;
for (int i = 0; i < dataGridView2.Rows.Count; ++i)
{
double d = 0;
Double.TryParse(dataGridView2.Rows[i].Cells[5].Value.ToString(), out d);
sum += d;
}
return sum;
}
Some considerations to take:
Make sure the data you are summing is in numeric form. Therefore the column type needs to be an integer, double or float (but surely not an nvarchar or varchar). This will ensure that the program does not go into error state when summing the values.
In the code above, taken from another answer in StackOverflow, the values in that column were parsed to double, to allow decimal numbers, and not simply whole numbers.
The sum needs to be stored in a variable of type double. It is up to you then what to do with it: Whether you want to store it in another place in the database or show it to the user in a label.
you have to sum the Values at your TextchangedEvent ,so please try this
protected void txtintroId_TextChanged(object sender, EventArgs e)
{
float total= 0;
foreach (GridViewRow gridViewRow in gridView.Rows)
{
lbltotal = (Label)gridViewRow.FindControl("lbltotal");
float rowValue = 0;
if (float.TryParse(lbltotal.Text.Trim(), out rowValue))
total += rowValue;
}
GridView1.FooterRow.Cells[3].Text = total.ToString();
}