簡體   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