2009-04-14 38 views
0

我有一個函數將LINQ結果綁定到窗體上的控件。下面的代碼工作,但我不能克服我應該爲複製/粘貼方面打耳光的感覺。有人可以幫我解決這個問題嗎?將控件綁定到LINQ的重構方法

謝謝!

private void BindDataToForm() 
    { 
     // Bind data to form 
     CaseNotesDataContext db = new CaseNotesDataContext(); 
     Table<CN_MaintItem> caseNotesItems = db.GetTable<CN_MaintItem>(); 

     // For each object 
     var contactType = from cType in caseNotesItems 
          where cType.CategoryID == 2 
          select cType.ItemDescription; 
     chkContactType.DataSource = contactType; 

     var contactLocation = from cLocation in caseNotesItems 
          where cLocation.CategoryID == 3 
          select cLocation.ItemDescription; 
     lkuContactLocation.Properties.DataSource = contactLocation; 

     var contactMethod = from cMethod in caseNotesItems 
          where cMethod.CategoryID == 4 
          select cMethod.ItemDescription; 
     lkuContactMethod.Properties.DataSource = contactMethod; 

     var contactWith = from cWith in caseNotesItems 
          where cWith.CategoryID == 5 
          select cWith.ItemDescription; 
     chkContactWith.DataSource = contactWith; 

     var domains = from d in caseNotesItems 
          where d.CategoryID == 6 
          select d.ItemDescription; 
     chkDomains.DataSource = domains; 
    } 

回答

3

我不知道,如果這真的是解決了什麼,但嘗試:

public static class MyExtentsions { 
    public IQueryable<string> GetItemDescriptions(this Table<CN_MaintItem> table, int cat) 
    { 
     return from x in table 
       where x.CategoryID == cat 
       select x.ItemDescription; 
    } 
} 

所以你可以像這樣拉信息:

using (CaseNotesDataContext db = new CaseNotesDataContext()) { 
    Table<CN_MaintItem> caseNotesItems = db.GetTable<CN_MaintItem>(); 

    chkContactType.DataSource = caseNotesItems.GetItemDescriptions(2); 
    lkuContactLocation.Properties.DataSource = caseNotesItems.GetItemDescriptions(3); 
    // etc... 
} 
0

可以 '縮短' 它做類似:

IQueryable<string> GetDescriptions(int cat) 
{ 
    return from x in caseNotesItems 
     where x.CategoryID == cat 
     select x.ItemDescription; 

} 

然後:

chkDomains.DataSource = GetDescriptions(6); 
... 
+0

你根本沒有通過這個表 – 2009-04-14 21:14:41

+0

哦,noes,friggen世界的盡頭,填補那個空白Nick ... – leppie 2009-04-14 21:17:03

1

訣竅是存儲顯式綁定控件所需的信息。您可以創建一個IDictionary<Control, Int32>來存儲每個控件的類別標識。然後,只需遍歷所有控件,在字典中查找id,並最後在條目存在時綁定它。您可以通過創建一個代表作爲值的字典來擴展此方法。這使您可以針對不同的控件執行不同的查詢。此外,您還可以使用Control.Tag屬性來存儲此信息。

相關問題