从列表框数据源中获取值

时间:2013-07-30 17:13:10

标签: c# database winforms data-binding

我有一个列表框,它是绑定到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 + "'");
    }

谢谢

1 个答案:

答案 0 :(得分:0)

ListBox包含两个成员: ValueMember DisplayMember

您可以从数据库查询中定义一个简单的对象:

 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)
            }
   }
相关问题