文本框中的Datagridview列和

本文关键字:Datagridview 列和 文本 | 更新日期: 2023-09-27 18:09:26

我想要datagridviewTextBox中的列和

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中插入数据,我想要GrandTotalTextBoxAMOUNT列的总和。

文本框中的Datagridview列和

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

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

从这里得到友好的帮助