我希望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
中插入数据,我希望AMOUNT
中GrandTotalTextBox
列的总和。
答案 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
的友好帮助下