【问题标题】:DataGridView issue - Calculated column value does not initially show up in DataGridViewDataGridView 问题 - 计算的列值最初未显示在 DataGridView 中
【发布时间】: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


【解决方案1】:

如果您的 TotalPrice 列未绑定,我会将其设为虚拟列并在 dataGrid 的 CellValueNeeded 事件中进行计算,否则在设置 DataGrid 的 DataSource 属性之前执行计算。根据您的用户将如何使用网格,您可能还需要了解更多细节,但这应该会让您朝着正确的方向前进。

【讨论】:

    【解决方案2】:

    在第一次绘制时,所有行都是新行...考虑更改您的 foreach 语句。

    应其他人的要求,以下是为您更改的代码/为您完成的工作:

    更改此块:

    foreach (DataGridViewRow row in dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !row.IsNewRow))
    {
        CalculateTotalPrice(row);
    }
    

    代替这个块:

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        CalculateTotalPrice(row);
    }
    

    【讨论】:

    • 这没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
    • 你好,这不是批评:我告诉他确切的问题是什么(在第一次绘制时,所有行都是新行),然后告诉他要改变什么(改变你的 foreach 语句)。 ..如果他这样做,它将解决他的问题。
    • 您提出了建议。这不是答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多