Ashfaque Baig Ashfaque Baig - 2 months ago 16
C# Question

datagridview column sum in textbox

I want

datagridview
column sum in
TextBox


private void AddButton_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Add(SNoTextBox.Text, PriceTextBox.Text, QtyTextBox.Text);

foreach(DataGridViewRow row in dataGridView1.Rows)
{
row.Cells[dataGridView1.Columns["Amount"].Index].Value = (Convert.ToDouble(row.Cells[dataGridView1.Columns["Price"].Index].Value) * Convert.ToDouble(row.Cells[dataGridView1.Columns["Qty"].Index].Value));
}
}


I'm using above code to insert data in
datagridview
and I want the sum of
AMOUNT
column in
GrandTotalTextBox
.

Answer

Just Try this:

private void AddButton_Click(object sender, EventArgs e)
{
    decimal amount =0;
    dataGridView1.Rows.Add(SNoTextBox.Text, PriceTextBox.Text, QtyTextBox.Text);

     foreach(DataGridViewRow row in dataGridView1.Rows)
     {
           row.Cells[dataGridView1.Columns["Amount"].Index].Value = (Convert.ToDouble(row.Cells[dataGridView1.Columns["Price"].Index].Value) * Convert.ToDouble(row.Cells[dataGridView1.Columns["Qty"].Index].Value));

           amount += Convert.ToDecimal(row.Cells[dataGridView1.Columns["Amount"].Index].Value);
      }
    GrandTotalTextBox.Text = amount.ToString();
}
Comments