datagridview列在文本框中的总和

时间:2016-09-28 09:10:04

标签: c#

我希望datagridview

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

我正在使用上面的代码在datagridview中插入数据,我希望AMOUNTGrandTotalTextBox列的总和。

2 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分:0)

还有一个Linq解决方案:

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

here

的友好帮助下