SQL 문을 사용하여 선택한 비즈니스 단위 (아래 예제에서 하드 코딩 됨)에 대해 직원의 성 및 이름이 (정렬 된) 목록 상자에 표시되는 응용 프로그램을 작성하고 있습니다. 사원 (액세스) 데이터베이스의 색인은 직원 번호입니다.- 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