2013-07-30 73 views
0

我有一個列表框,它是數據綁定到accdb文件並顯示一列的內容,它鏈接到的dataBindingSource也被過濾 - 這可以正常工作(但可能會影響什麼我即將問)。例如,我想知道如何從所選項目的全部記錄中提取一個值。列表框當前顯示的是姓氏 - 這就是你能看到的所有信息,我怎樣才能提取未顯示但存在於數據綁定源中的客戶姓名?從列表框中獲取數據源

這是代碼中使用的填充列表框:

public frmCustomer(string Input) 
    { 
     InitializeComponent(); 
     this.customersTableAdapter.Fill(this.dSSystem.Customers); 
     this.catsTableAdapter.Fill(this.dSSystem.Cats); 

     // Display Customer Record 
     int lvRecIdx = customersBindingSource.Find("AccRef", Input); 
     customersBindingSource.Position = lvRecIdx; 

     // Fetch Cats Owned 
     catsBindingSource.Filter = ("CustRef = '" + Input + "'"); 
    } 

謝謝

+0

請同時給我們展示一些代碼並確保爲WPF/Asp.NET/WinForms附加標籤,以便您得到正確答案。 –

+0

在這種情況下,您應該從數據源中選擇2列訪問數據庫。你也應該選擇表的「主鍵」。 –

+0

@FabianBigler我目前沒有任何代碼顯示,因爲我不確定如何引用該記錄中的另一個字段,如果有幫助,我添加了用於填充列表框的代碼。 – MrDKOz

回答

1

一個ListBox包含兩個成員組成:ValueMemberDisplayMember

你可以定義哪些你是從你的數據庫查詢填充一個簡單的對象:

public class SomeItem 
{ 
     public int Key { get; set; } 
     public string DisplayText { get; set; } 
     public string Column1 { get; set; } 
     public string Column2 { get; set; } 
     ...etc... 
} 

你的實現可能看起來像這樣(一些模型數據):

var items = new List<SomeItem>(); 
    var item = new SomeItem(); 
    item.Key ="key1"; 
    item.DisplayText = "value1"; 
    item.Column1 = "col1"; 
    item.Column2 = "col2"; 
    items.Add(item); 
    listBox1.DataSource = items; 
    listBox1.DisplayMember = "DisplayText"; //User will see your DisplayText 
    listBox1.ValueMember = "Key"; //The key which is unique and your Primary Key on your database 

在此基礎上您選擇的值,您可以查詢您的物品並獲得物品:

var key = (int)listBox1.SelectedValue; 
    foreach (var existingItem in items) 
    { 
      if (existingItem.Key == key) 
      { 
       //woohoo got it! 
       Debug.Print(existingItem.Column1) 
       Debug.Print(existingItem.Column2) 
      } 
    } 
+0

已排序。非常感謝你! – MrDKOz