【发布时间】:2014-04-30 18:54:38
【问题描述】:
我正在使用 C#、.Net 4.5、Entity Frameworks 6.1 开发一个 Windows 窗体应用程序
我正在使用以下代码填充 DataGridView 控件。
var context = new MyVisionBidModelEntities();
bidItemMaterialBindingSource.DataSource =
context.BidItemMaterials.Where(c => c.BidItemID == selectedItem.BidItemID).ToList();
dataGridView1.DataSource = bidItemMaterialBindingSource;
然后我使用以下代码设置计算“TotalPrice”列的值。
foreach (DataGridViewRow row in dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !row.IsNewRow))
{
CalculateTotalPrice(row);
}
private void CalculateTotalPrice(DataGridViewRow row)
{
object a = row.Cells[1].Value;
object b = row.Cells[2].Value;
object c = row.Cells[3].Value;
double aNumber = 0;
double bNumber = 0;
double cNumber = 0;
if (a != null)
aNumber = Double.Parse(a.ToString());
if (b != null)
bNumber = Double.Parse(b.ToString());
if (c != null)
cNumber = Double.Parse(c.ToString());
row.Cells["TotalPrice"].Value = aNumber * bNumber * cNumber;
row.Cells["TotalPrice"].ValueType = typeof(double);
}
当我最初查看 DataGridView 控件时,所有行和列都是可见的,但是,TotalPrice 列具有空值。
当我重新执行上面的代码时,DataGridView 现在有了 TotalPrice 值。
我尝试过执行 DataGridView.Refresh、DataGridView.Update 等。但最初无法显示计算列。它适用于第二次油漆。
我错过了什么吗?
【问题讨论】:
-
您可能需要计算总数作为查询的一部分,才能按您的意愿工作。
-
在第一次绘制时,所有行都是新行...考虑更改您的 foreach 语句。
-
@JohnGnazzo 我认为
MaxOvdriv不妨告诉你我要做什么,但由于不清楚,我会发表评论。当您在foreach之前执行此代码dataGridView1.DataSource = bidItemMaterialBindingSource;时,TotalPrice列为空,因为您尚未完成 foreach 并为其设置值。首先 - 确保所有列都有正确的数据,并在最后绑定数据源。 -
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# .net winforms entity-framework datagridview