简体   繁体   中英

How to connect listbox to table c# winforms

I have a table and a form with a listBox1 . I want values from one column from the table will be displayed in the listBox1 . For example:

the table columns: Id , Name , Phone

the table rows:

        1 , abc , 123 

        2 , atg , 124

        24 , awt, 155

in the listBox1:

         1

         2

         24

and I also need to know on which one did I clicked from the listBox1. For example: I clicked on the '24' in the listBox1 and the value '24' will show in textBox1

Did you set these properties?

listBox1.DataSource = yourTable;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";

In this way, your listbox will show the column name, but when you click an item you could get the value (ID) associated with that name

    private void ListBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1)
        {
            int personID = Convert.ToInt32(listBox1.SelectedValue.ToString());
            .......
        }
    }

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