2017-08-03 128 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