简体   繁体   中英

C# - How do I find the database key of a Listbox item?

I am writing an application where the surname and first name of an employee is shown in a (sorted) listbox - for a selected business unit (hard coded in example below) using an sql statement. The index of the employee (Access) database is the employee number.

When the item is selected from the listbox I can't find a way to determine the employee number that enables me to read the database to obtain attributes about the employee on a new form. I think the trick maybe using keyvaluepair but need some guidance on how this is coded. A sample of the code is below and thanks in anticipation of your help.

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)
        {

        }
    }
}

I would store the data from the DB in a Dictionary, let's say

Dictionary<int,String[]>

where the key is ID and the array is composed of Name and Surname. Then you populate the listBox with the Dictionary data.

Not an appropriate answer but an idea:

Maybe you could try something like converting the result into an array or dictionary

listBox1.DataSource = <Array or Dictionary>;
listBox1.DisplayMember = "NameOfColumnToBeDisplayed";
listBox1.ValueMember = "NameOfColumnToUseValueFrom";

And the Display != Value (eg value would be your employee id)

not sure if you can add a hidden field into the listbox. however if you store the query you received into a variable which is retained (maybe a datatable as opposed to using a datareader), then when a user clicks to select an option from the listbox you can use that to find the associated record in the query using the index of the listbox selected item.

however you must ensure that the query does the sorting of the results and not the listbox.

Mike

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM