我有两个盒子,我想从sql填充第一个,第二个基于第一个(查询sql)
public void Country()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT CountryName FROM Country", conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["CountryName"] = "";
dt.Rows.InsertAt(dr, 0);
this.country.DisplayMember = "CountryName";
this.country.ValueMember = "CountryName";
this.country.DataSource = dt;
}
}
}
}
public void City()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT CityName FROM City", conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["CityName"] = "";
dt.Rows.InsertAt(dr, 0);
this.country.DisplayMember = "CityName";
this.country.ValueMember = "CityName";
this.country.DataSource = dt;
}
}
}
}
T A B L E S
国家
PK CountryName
城市
PK CityName
FK CountryName
我相信我应该改变City的SqlCommand,也许是WHERE语句?因此,如果选择Country1,则在City框中仅显示City1,如果Country2则显示City2,依此类推。 我怎么能这样排序,谁知道呢?感谢
答案 0 :(得分:2)
SELECT DISTINCT CityName FROM City where CountryName =@CountryName
使用上面的where子句更改select语句,然后可以使用this.country.SelectedValue
您可以在第一个组合框选择的索引更改事件上加载第二个组合框。使用where条件调用第一个组合框选择的索引更改事件中的City()
以根据国家/地区过滤城市
相关代码的几个链接: