繁体   English   中英

C# - 如何找到列表框项的数据库键?

[英]C# - How do I find the database key of a Listbox item?

我正在编写一个应用程序,其中员工的姓氏和名字显示在(排序的)列表框中 - 对于使用 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)
        {

        }
    }
}

我会将数据库中的数据存储在字典中,比方说

Dictionary<int,String[]>

其中键是 ID,数组由 Name 和 Surname 组成。 然后用字典数据填充列表框。

不是一个合适的答案,而是一个想法:

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

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

和 Display != Value(例如,值将是您的员工 ID)

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

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

麦克风

暂无
暂无

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

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