简体   繁体   English

从列表框数据源获取值

[英]Fetch Value from Listbox Datasource

I have a list box that is data bound to a accdb file and is display the contents of one column, the dataBindingSource that it is linked to has also been filtered - this works fine (but may effect what I'm about to ask). 我有一个列表框,该列表框的数据绑定到accdb文件,并显示一列的内容,它链接到的dataBindingSource也已被过滤-可以正常工作(但可能会影响我要问的内容)。

I would like to know how to pull a value from the selected items full record, for example. 例如,我想知道如何从所选项目的全记录中提取一个值。 The list box currently displays the surname - that is all you can see, how can I pull the customers forename which isn't displayed but does exist within the data bound source? 列表框当前显示姓-您可以看到的所有信息,如何提取未显示但在数据绑定源中存在的客户姓?

This is the code used the populate the list box: 这是用于填充列表框的代码:

    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 + "'");
    }

Thank you 谢谢

A ListBox contains of two members: A ValueMember and a DisplayMember . ListBox包含两个成员: ValueMemberDisplayMember

You could define a simple object which you are filling from your data base query: 您可以定义一个简单的对象,该对象将从数据库查询中填充:

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

Your implementation could look something like this (some mockup data): 您的实现可能看起来像这样(一些模型数据):

   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

Then based on the value you selected, you can query through your items and get the item: 然后,根据您选择的值,您可以查询项目并获取该项目:

   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)
            }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM