【问题标题】:Fetch Value from Listbox Datasource从列表框数据源中获取值
【发布时间】:2013-07-30 17:13:10
【问题描述】:

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

谢谢

【问题讨论】:

  • 请给我们看一些代码,并确保附上WPF / Asp.NET / WinForms的标签,这样你就会得到正确的答案。
  • 在这种情况下,您应该从数据源中选择 2 列访问数据库。您还应该选择表格的primary key
  • @FabianBigler 我目前没有任何代码可显示,因为我不确定如何引用该记录中的另一个字段,如果是,我添加了用于填充列表框的代码有帮助。
  • @SeyedMortezaMousavi 列表框不允许我选择多个要显示的列,这是你要我做的吗?
  • @MoonPunch 列表框中的每个项目都有两个主要属性:ValueText。值不会显示给最终用户,但会向用户显示文本。

标签: c# database winforms data-binding


【解决方案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

然后根据你选择的值,就可以通过你的item查询得到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)
            }
   }

【讨论】:

  • 已排序。非常感谢!
猜你喜欢
  • 2022-10-13
  • 2022-01-11
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
  • 2021-06-27
  • 1970-01-01
相关资源
最近更新 更多