我想计算总价并在数据网格视图中显示它。第四列不从数据库中检索信息,因此我不知道如何执行此操作。这是GUI的样子:
这是我到目前为止的代码......
double colTotal = 0; //set column total to 0
foreach (DataRow currentRow in itemDS.Tables[0].Rows)
{
// add to data grid view
invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString());
//Decalare variables for item quantity and price
var itemQuant = Convert.ToDouble(currentRow[1]);
var priceEach = Convert.ToDouble(currentRow[3]);
//Multiply the item quantity by the item price
double subTotal = itemQuant * priceEach;
//do this for each row
colTotal += subTotal;
}
//Display subtotal
subTotalOutput.Text = colTotal.ToString();
//Calculate tax
double tax = colTotal * .073;
//Display total tax
taxOutput.Text = Convert.ToString(tax);
//Add the subtotal and the total tax
double totPrice = colTotal + tax;
//Display total price
totalOutput.Text = Convert.ToString(totPrice);
}
答案 0 :(得分:1)
我相信您可以在填充网格之前执行subTotal计算,并在末尾添加subTotal变量以调用dataGrid.Rows.Add()。像这样:
foreach (DataRow currentRow in itemDS.Tables[0].Rows)
{
//Decalare variables for item quantity and price
var itemQuant = Convert.ToDouble(currentRow[1]);
var priceEach = Convert.ToDouble(currentRow[3]);
//Multiply the item quantity by the item price
double subTotal = itemQuant * priceEach;
// add to data grid view
invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString(), subTotal);
//do this for each row
colTotal += subTotal;
}
答案 1 :(得分:0)
我首先要说的是,使用DataGridView控件的DataSource属性可以让您的生活更轻松,但是为了解决您当前设置的问题,我只需移动一些代码并按照以下方式执行:
double subTotal = itemQuant * priceEach;
invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString(), subTotal.ToString());