在C#中从数据库显示列表框中的项目 [英] Show items in listbox from database in C#

查看:112
本文介绍了在C#中从数据库显示列表框中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个表 Countries Websites 的数据库.我使用以下语句在listbox1中显示所有国家/地区名称:

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();
}

但是,基于用户在listbox1中选择的项目,我知道我希望列表2显示与数据库中的国家/地区链接的相关网站.网站表中的外键是 CountryIDFK ,我想显示第二个表的字段 WebsiteName .

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.

我不知如何显示listbox2中的项目.我不想将它们添加到第二个列表框中,而只是根据用户选择的国家/地区进行显示.有人可以帮忙吗?

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 ?

推荐答案

首先,您可以绑定数据源.这意味着您可以将DataTable或对象列表绑定到列表框.示例在此处可用:

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.

然后,您可以使用SelectedValueChanged事件处理程序,上面的示例中也对此进行了演示.在处理程序方法中,您只需填充第二个列表框.

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.

这篇关于在C#中从数据库显示列表框中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆