C# C-如何查找列表框项的数据库键?
我正在编写一个应用程序,其中员工的姓氏和名字显示在一个排序的列表框中,用于下面示例中使用sql语句硬编码的选定业务单元。employee Access数据库的索引是员工编号 当从列表框中选择该项时,我找不到一种方法来确定员工编号,该编号使我能够读取数据库以获取新表单上员工的属性。我认为这个技巧可能使用keyvaluepair,但需要一些关于如何编码的指导。下面是一个代码示例,非常感谢您的帮助C# C-如何查找列表框项的数据库键?,c#,database,indexing,listbox,C#,Database,Indexing,Listbox,我正在编写一个应用程序,其中员工的姓氏和名字显示在一个排序的列表框中,用于下面示例中使用sql语句硬编码的选定业务单元。employee Access数据库的索引是员工编号 当从列表框中选择该项时,我找不到一种方法来确定员工编号,该编号使我能够读取数据库以获取新表单上员工的属性。我认为这个技巧可能使用keyvaluepair,但需要一些关于如何编码的指导。下面是一个代码示例,非常感谢您的帮助 using System; using System.Collections.Generic; usin
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,数组由名称和姓氏组成。
然后用字典数据填充列表框。这不是一个合适的答案,而是一个想法: 也许您可以尝试将结果转换为数组或字典
listBox1.DataSource = <Array or Dictionary>;
listBox1.DisplayMember = "NameOfColumnToBeDisplayed";
listBox1.ValueMember = "NameOfColumnToUseValueFrom";
还有显示器值,例如值将是您的员工id,不确定是否可以在列表框中添加隐藏字段。但是,如果您将收到的查询存储到一个变量中,该变量可能保留在数据表中,而不是使用数据读取器,那么当用户单击从列表框中选择选项时,您可以使用该选项使用列表框所选项的索引查找查询中的关联记录 但是,您必须确保查询对结果进行排序,而不是对列表框进行排序
Mike显示的数据将以姓氏、名字的格式显示不止一列,因此我不确定DisplayMember是否允许这样做。我以前尝试过使用数组,但由于列表在列表框中自动排序,因此项目将不匹配。他可以将两个列作为字符串连接起来。这实际上取决于他的目的以及如何成功检索他可以轻松操纵的集合。自从我上次接触C已经有一段时间了,但我记得我做了一些非常相似的事情。不过,这只是一个想法。谢谢迈克-你的最后一点是我没有考虑过的,应该会让我的生活更轻松。没问题,你甚至可以将listbox的数据源绑定到datatable,并在listbox上设置valuemember和displaymember属性。