c# - 嗨,我正在尝试更改单元格值更改事件中 gridview 列的值,但每次发生时我都没有得到正确的输出
问题描述
我有三列 Sold QTY ,Return QTY 和 Transaction QTY 现在我想通过从 Sold QTY 中减去 Return QTY 来更改 Sold QTY 的值,并将结果放在 SoldQTY 列中。以下是我尝试过的代码
private void dgvSalesItem_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dgvSalesItem.Rows.Count > 0)
{
int counter;
double SoldQTY = 0;
double reutrnQTY = 0;
double TPrice = 0;
double resultant = 0;
string PID = dgvSalesItem.CurrentRow.Cells["Column9"].Value.ToString();
if (dgvSalesItem.CurrentRow.Cells["Column11"].Value != null)
{
SoldQTY = clsCN.num_repl(dgvSalesItem.CurrentRow.Cells["Column11"].Value.ToString());
}
if (dgvSalesItem.CurrentRow.Cells["dgvtxtSoldQTY"].Value != null)
{
reutrnQTY = clsCN.num_repl(dgvSalesItem.CurrentRow.Cells["dgvtxtSoldQTY"].Value.ToString());
}
if (dgvSalesItem.CurrentRow.Cells["Column12"].Value != null)
{
TPrice = clsCN.num_repl(dgvSalesItem.CurrentRow.Cells["Column12"].Value.ToString());
}
if (!(reutrnQTY > SoldQTY))
{
resultant = SoldQTY - reutrnQTY;
}
dgvSalesItem.CurrentRow.Cells["Column12"].Value = resultant;
}
解决方案
如果您将 DataGridView 绑定到 DataTable,然后使用 DataColumn 的 Expression 属性来计算总和,您的生活会容易得多
例子:
DataTable dt = new DataTable();
dt.Columns.Add("SoldQty", typeof(int));
dt.Columns.Add("ReturnQty", typeof(int));
//i'd just do the sum, not bother with the IF bit
dt.Columns.Add("ResultQty", typeof(int)).Expression = "[SoldQty] - [ReturnQty]";
//but you can do this if you really want to only calc when sold>return
dt.Columns.Add("ResultQty", typeof(int)).Expression = "IIF([SoldQty] > [ReturnQty], [SoldQty] - [ReturnQty], 0)";
datagridviewWhatever.DataSource = dt;
有关可以使用计算列(表达式)做什么的更多信息,请参阅手册