Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中显示来自数据库的列表框中的项目#_C#_Database_Listbox - Fatal编程技术网

C# 在C中显示来自数据库的列表框中的项目#

C# 在C中显示来自数据库的列表框中的项目#,c#,database,listbox,C#,Database,Listbox,我有一个数据库,有两个表国家和网站。我在列表框1中显示所有国家的名称,并附带以下语句: try { connection.Open(); using (OleDbCommand command = new OleDbCommand()) { command.Connection = connection; command.CommandText = "SELECT CountryName FROM Countries ";

我有一个数据库,有两个表
国家
网站
。我在列表框1中显示所有国家的名称,并附带以下语句:

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();
}
但是,根据用户在列表框1中选择的项目,我希望列表框2显示数据库中链接到该国家的相关网站。网站表中的外键是
CountryIDFK
,我想显示第二个表的字段
WebsiteName


我不知怎的不知道如何显示listbox2中的项目。我不想将它们添加到第二个列表框中,而只是根据用户选择的国家显示。有人能帮忙吗?

首先,您可以绑定数据源。这意味着您可以将数据表或对象列表绑定到listbox。示例在此处可用: 这样,您将能够在列表框项目列表中存储您的Id和国家名称

之后,您可以使用SelectedValueChanged事件处理程序,这也在上面的示例中演示过。在handler方法中,您只需填充第二个列表框

对于考试:

tbl_tableFilds: ID,Title
在EF中:

var Result=tbl_Table.where().tolist();
ListBox1.Datasource=Result;
ListBox1.DisplyMemmber="Title";
ListBox1.ValueMember="ID";
var Result=tbl_Table.where().tolist();
foreach(var item in Result) {
  ListBox1.items.Add(item.Title);
  }
另一种方式是:

在EF中:

var Result=tbl_Table.where().tolist();
ListBox1.Datasource=Result;
ListBox1.DisplyMemmber="Title";
ListBox1.ValueMember="ID";
var Result=tbl_Table.where().tolist();
foreach(var item in Result) {
  ListBox1.items.Add(item.Title);
  }

在列表框的SelectedIndexChanged事件中,使用所选值并查询数据库并返回与所选项目匹配的记录。您好,欢迎使用StackOverflow。请编辑您的答案,通过{}按钮突出显示代码,目前还不清楚。谢谢。我自己也尝试过格式化(编辑等待同行评审)。