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