【问题标题】:DataGridView Column Will Not Show Values That Were Set. They show up blank in the GUIDataGridView 列将不显示已设置的值。它们在 GUI 中显示为空白
【发布时间】:2018-01-11 12:41:51
【问题描述】:

我的最终目标是替换被拉表的外键 ID 以获取人名。任何帮助都会很棒。我使用 EF6 上下文 DbSet 作为 DataGridView 的绑定源。

它会拉出整个表格,但这对于 GUI 来说还不够干净。所以我最终删除了 Id 列和其他列。然后我添加一个名为 Person Name 的新列。

从字面上看,一切都按照我的需要完美运行。它只是不显示 DGV 单元格中人员姓名的值。

using (var ctx = new myDbContext())
{ 
    BindingSource bSrc = new BindingSource();
    bSrc.DataSource = ctx.myDbSet.ToList();
    myDataGridView.DataSource = bSrc;
    myDataGridView.Refresh();
}
myDataGridView.Columns.Add("originalPerson", "Person Name");

myDataGridView.AutoGenerateColumns = false;

myDataGridView.Columns.Remove("Id");
myDataGridView.Columns.Remove("DateModified");
myDataGridView.Columns.Remove("DateCreated");

using (var ctx = new myDbContext())
{
    foreach (DataGridViewRow r in myDataGridView.Rows)
    {

        int pId= (Int32)r.Cells[0].Value;
        string name = ctx.personsTable.FirstOrDefault(p => p.Id == pId).name;
//Where I set the values.
        r.Cells[myDataGridView.Columns.Count - 1].Value = name.ToUpper();
    }
}

myDataGridView.Columns.Remove("personsTableId");

if (myDataGridView!= null)
{
    myDataGridView.Columns[myDataGridView.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}

如果有人认为我应该以另一种方式来做,我会全力以赴,我觉得这很快就会变得一团糟。提前致谢!我继续展示了我所拥有的一切。

【问题讨论】:

  • 你能通过单步调试代码设置断点来定位问题吗?
  • 当我单步执行程序时,它会很好地设置值并将名称放在正确的单元格中。 GUI 只是显示我最右边的/新列,就像那里什么都没有。我觉得这与我向 DGV 中添加值有关,而无需进行一些重绘或刷新,但是更新/刷新不起作用。
  • 你发布的所有代码在做什么?
  • 表单加载基本上是在 Visual Studio IntializeComponents 生成方法之后。

标签: c# windows winforms datagridview entity-framework-6


【解决方案1】:

我昨天回答了一个类似的问题,我会为您推荐相同的解决方案:

Binding a value from a parent table into a DataGridView's text box using the foreign key

另外,我建议您隐藏它们Visible = false,而不是删除您不想要的列。这样,您可以稍后在需要时引用这些值/列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多