我正在編寫一個應用程序,其中僱員的姓氏和名字顯示在(已排序)列表框中 - 對於選定的業務單位(在以下示例中用硬編碼表示)使用sql語句顯示。員工(Access)數據庫的索引是員工編號。C# - 如何找到Listbox項目的數據庫項?
當從列表框中選擇項目時,我無法找到確定員工編號的方法,該編號使我能夠讀取數據庫以獲取有關新窗體上員工的屬性。我想訣竅可能是使用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)
{
}
}
}
感謝邁克 - 你的最後一點是我沒有考慮過的事情,應該讓我的生活變得更輕鬆。 – Markys
沒有問題,您甚至可以更好地將列表框的數據源綁定到數據表,並在列表框上設置valuemember和displaymember屬性。 – Micktommyord