简体   繁体   English

如何将列表框连接到表C#WinForms

[英]How to connect listbox to table c# winforms

I have a table and a form with a listBox1 . 我有一张桌子和一个带有listBox1的表单。 I want values from one column from the table will be displayed in the listBox1 . 我希望表中一列的值将显示在listBox1 For example: 例如:

the table columns: Id , Name , Phone 表格栏:ID,Name,Phone

the table rows: 表格行:

        1 , abc , 123 

        2 , atg , 124

        24 , awt, 155

in the listBox1: 在listBox1中:

         1

         2

         24

and I also need to know on which one did I clicked from the listBox1. 而且我还需要知道我从listBox1中单击了哪一个。 For example: I clicked on the '24' in the listBox1 and the value '24' will show in textBox1 例如:我在listBox1单击了“ 24”,值“ 24”将显示在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 这样,您的列表框将显示列名称,但是当您单击一个项目时,您可以获得与该名称关联的值(ID)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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