DataGridView问题-计算列值最初未显示在DataGridView中
本文关键字:DataGridView 显示 问题 计算 | 更新日期: 2023-09-27 18:00:55
我正在使用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列的值为Null。
当我重新执行上面的代码时,DataGridView现在具有TotalPrice值。
我尝试过执行DataGridView.Refresh、DataGridView.Update等操作,但无法使计算列最初显示。第二层油漆效果很好。
我是不是错过了什么?
如果您的TotalPrice列没有绑定,我会将其设为虚拟列,并在dataGrid的CellValueNeeded
事件中进行计算,否则在设置dataGrid的DataSource属性之前执行计算。根据用户使用网格的方式,你可能还需要锻炼一些细节,但这应该会让你朝着正确的方向前进。
在第一次绘制时,所有行都是新行。。。考虑改变你的foreach语句。
根据其他人的要求,以下是为您更改的代码/为您完成的工作:
更改此块:
foreach (DataGridViewRow row in dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !row.IsNewRow))
{
CalculateTotalPrice(row);
}
对于这个块:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
CalculateTotalPrice(row);
}