【发布时间】:2018-03-24 14:17:45
【问题描述】:
我正在编写一个应用程序,其中员工的姓氏和名字显示在(排序的)列表框中 - 使用 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)
{
}
}
}
【问题讨论】:
标签: c# database indexing listbox