如何在网格视图与IFCondition列之间求和值?



我在gridview中有3列,Column_A, Column_B和Column_total。然后我在Column_A和Column_B之间做简单的计算,并把它放在Column_total..例如:当我在行Column_A中输入值1,在行Column_B中输入值1时,Column_total显示结果2。下面的代码很简单:

private void Gdv_CellEndEdit(object sender, GridViewCellEventArgs e)
{
foreach (GridViewDataRowInfo Val in Gdv.SelectedRows)
{
Val.Cells["Column_Total"].Value =  Convert.ToInt32(Val.Cells["Column_A"].Value) + Convert.ToInt32(Val.Cells["Column_B"].Value);
}
}


但是在Column_total中,当我删除Column_A中的值时,仍然显示结果。

我想要的,当我在Column_A中输入值时,Column_total显示结果,然后当我在Column_A中删除值时,Column_total将返回空并且不会显示任何结果。有人能帮忙吗?

你的方法没有被召回来重新分配更新的值,我只能猜测你的。value是一个字符串,因为你正在使用转换,没有指定。

private void Gdv_CellEndEdit(object sender, GridViewCellEventArgs e)
{
bool _; /*Throw away value true/false output not needed, 
prevents compiler warning.*/
foreach (GridViewDataRowInfo Val in Gdv.SelectedRows)
{
_ = int.TryParse(Val.Cells["Column_A"].Value, out a);
_ = int.TryParse(Val.Cells["Column_B"].Value, out b);
Val.Cells["Column_Total"].Value = (a != 0 || b != 0) ? (a + b) : "";
//If a or b is not 0, as int cannot be null; will sum(a+b), else return "" empty.
//Can change the or || to && if you require both to have values > 0.
}
}

最后…
同意@JohnG,解决我的问题的方法是使用列表达式。
这是我的项目的最后一个代码片段:

// Create second column.
DataColumn Col_A = new DataColumn();
Col_A .DataType = System.Type.GetType("System.Decimal");
Col_A .ColumnName = "Column_A";
// Create second column.
DataColumn Col_Total = new DataColumn();
Col_Total .DataType = System.Type.GetType("System.Decimal");
Col_Total .ColumnName = "Column_total";
Col_Total .Expression = "Column_A * Column_B";
// Add columns to DataTable.
dt.Columns.Add(Col_A);
dt.Columns.Add(Col_Total);
DataView view = new DataView(dt);
dgv.DataSource = view;

我添加了两个新列,命名为"Col_A"one_answers";Col_Total"在求和列中,列"Column_B"从显示mysql数据源的gridview中获得。

它真的很有效,我不知道还有什么比这更好的吗?

感谢你们回答我前面的问题。

最新更新