C# - 如何查找Listbox项目的数据库键?

3
我正在编写一款应用程序,其中一个员工的姓和名将以(排序)列表框的形式显示 - 对于选择的业务单元(在下面的示例中是硬编码),使用sql语句。Access数据库中的员工编号是员工的索引。
当从列表框中选择项目时,我找不到一种确定员工编号的方法,这使我能够读取数据库以获取有关员工的属性(在新表单上)。我认为诀窍可能是使用keyvaluepair,但需要有关如何编写代码的指导。下面是部分代码的样例,在此感谢您的帮助。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private OleDbConnection connection = new OleDbConnection();
        public Form1()
        {
            InitializeComponent();
            connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mark\Documents\Employee.accdb;Persist Security Info=False;";
            listBox1_Load();
            }

    void listBox1_Load()
        {
            try
            {
            // Open database and select the data to be shown in the List Box - hard-coded example here
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            string query = "select ID, FirstName, Surname from Employee where BusinessUnit = 'Finance'";
            command.CommandText = query;

            OleDbDataReader reader = command.ExecuteReader();

            // Read records returned by the query and populate the list box with the employee name
            while (reader.Read())
            {
                listBox1.Items.Add(reader["Surname"] + ", " + reader["FirstName"]);
            }
            connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error " + ex);
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
3个回答

1

不确定是否可以将隐藏字段添加到列表框中。但是,如果您将收到的查询存储到保留的变量中(可能是一个数据表,而不是使用数据读取器),那么当用户单击以从列表框中选择选项时,您可以使用它来查找查询中相关的记录,使用列表框所选项目的索引。

但是,您必须确保查询对结果进行排序,而不是列表框。

迈克


谢谢Mike - 你最后提到的一点是我没有考虑过的,应该会让我的生活变得更容易。 - Markys
没问题,你甚至可以将列表框的数据源绑定到一个数据表,并在列表框上设置valuemember和displaymember属性。 - Micktommyord

1
我会将数据库中的数据存储在一个字典中,比如说
Dictionary<int,String[]>

其中键是ID,数组由名字和姓氏组成。 然后您使用字典数据填充listBox。


1

这并不是一个合适的答案,但是是个想法:

也许您可以尝试将结果转换为数组或字典

listBox1.DataSource = <Array or Dictionary>;
listBox1.DisplayMember = "NameOfColumnToBeDisplayed";
listBox1.ValueMember = "NameOfColumnToUseValueFrom";

显示 ≠ 值 (例如,值可以是您的员工ID)


显示的数据将以“姓,名”的格式呈现在多列中,因此我不确定 DisplayMember 是否允许这样的显示。我先前尝试使用数组,但由于列表框会自动排序,项目将无法匹配。 - Markys
他可以将两列作为字符串连接起来。这真的取决于他的目的以及如何成功地检索到一个他可以轻松操作的集合。我已经有一段时间没有接触C#了,但我记得做过非常类似的事情。不过,这只是一个想法。 - abr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接