我有一个包含两个表的数据库Countries
and Websites
。我使用以下语句显示 listbox1 中的所有国家/地区名称:
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 中的项目。我不想将它们添加到第二个列表框中,而是只是根据用户选择的国家/地区进行显示。有人可以帮忙吗?
首先,您可以绑定数据源。这意味着您可以将 DataTable 或对象列表绑定到列表框。示例如下:https://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.datasource%28v=vs.110%29.aspx这样您就可以将您的 ID 和国家/地区名称存储在列表框项目列表中。
之后,您可以使用 SelectedValueChanged 事件处理程序,这也在上面的示例中进行了演示。在处理程序方法中,您只需填充第二个列表框。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)