Ashfaque Baig
Ashfaque Baig

Reputation: 53

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.

Upvotes: 2

Views: 1996

Answers (2)

Mong Zhu
Mong Zhu

Reputation: 23732

There would also be a Linq Solution to this:

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));
    }
}

List<decimal> list = dataGridView1.Rows
         .OfType<DataGridViewRow>()
         .Select(r => Convert.ToDecimal(r.Cells["Amount"].Value.ToString()))
         .ToList();

GrandTotalTextBox.Text = list.Sum().ToString();

with friendly help from here

Upvotes: 0

Inside Man
Inside Man

Reputation: 4372

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();
}

Upvotes: 2

Related Questions