Show items in listbox from database in C#

陌路散爱 提交于 2021-02-05 08:38:10

问题


I have have a database with two tables Countries and Websites. I am displaying all countrynames in listbox1 with the following statement:

try
{

    connection.Open();
    using (OleDbCommand command = new OleDbCommand())
    {
        command.Connection = connection;
        command.CommandText = "SELECT CountryName FROM Countries ";
        //whenever you want to get some data from the database
        using (OleDbDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                listBox1.Items.Add(reader["CountryName"].ToString());
            }
        }
    }
}
catch (Exception l)
{
    MessageBox.Show("Error:" + l);
}
finally
{
    connection.Close();
}

However know based on what Item the user selects in listbox1 I want listbox two to display the relevant websites that are linked to the country in the database. The foreign key in the website table is CountryIDFK and I want to display the field WebsiteName of the second table.

I somehow don't know how to show the items in listbox2. I don't want to add them in the second listbox but rather just show based on what country the user has selected. Can someone assist please ?


回答1:


First of all, you could bind your datasource. This means that you could bind DataTable or object list to your listbox. Example is avaliable here: https://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.datasource%28v=vs.110%29.aspx This way you will be able to store your Id and country name in you listbox items list.

Afterwards you could use SelectedValueChanged event handler which is also demonstrated in the example above. In the handler method you just populate your second listbox.




回答2:


For Exam:

tbl_tableFilds: ID,Title

in EF:

var Result=tbl_Table.where().tolist();
ListBox1.Datasource=Result;
ListBox1.DisplyMemmber="Title";
ListBox1.ValueMember="ID";

another way is :

in EF:

var Result=tbl_Table.where().tolist();
foreach(var item in Result) {
  ListBox1.items.Add(item.Title);
  }


来源:https://stackoverflow.com/questions/32347339/show-items-in-listbox-from-database-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!