2017-08-03 126 views
1

我的最终目标是替换拉出的表的外键ID以获取人名。任何帮助,这将是伟大的。我使用EF6上下文DbSet作为DataGridView的绑定源。DataGridView列将不显示设置的值。它们在GUI中显示为空白

虽然这对于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; 
} 

如果有人认为我应该做的另一种方式,我是所有的耳朵,我觉得这很乱。提前致谢!我继续展示我所拥有的一切。

+0

你可以找到问题的步骤通过代码设置断点..? – MethodMan

+0

当我通过该程序时,它设置的值很好,并将名称放在正确的单元格中。图形用户界面刚好显示出我的最右边/新列,就像那里什么也没有。我觉得这与我在DGV中添加值时没有经过一些重绘或刷新有关,但更新/刷新不起作用。 – Byrd

+0

你在做什么事情你所发布的所有代码..? – MethodMan

回答

0

昨天我回答了类似的问题,我会建议相同的解决方案为您提供:

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

而且 - 而不是删除列的,你不想要的,我会建议他们躲在Visible = false。这样,如果您需要它们,您可以稍后参考这些值/列。

+0

因此,没有解决我的问题。不过,它给了我一个更好的主意。我放弃了BindingSource,因为这是导致这么多垃圾代码的原因。我现在只是遍历DbContext.table.ToList();然后手动添加它。它更漂亮,我不确定我早些时候在想什么......我只是非常喜欢使用BindingSource。 – Byrd