彼此基于SQL C#的组合框填充 [英] combobox population based on each other sql c#

查看:70
本文介绍了彼此基于SQL C#的组合框填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个框,我想从sql中填充第一个,并根据第一个(也查询sql)填充第二个。

i have 2 boxes, i'd like to populate the 1st from sql and the 2nd based on the first (querying sql too)

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

国家

PK CountryName

PK CountryName

城市

PK城市名称

FK国家名称

我相信我应该更改City的SqlCommand,也许是WHERE语句?因此,如果选择了Country1,则在City框中仅显示City1,如果Country2然后是City2,依此类推。
我怎么能排序,谁知道?谢谢

I believe i should change City's SqlCommand, maybe a WHERE statement? so if Country1 is chosen, in the City box it only shows City1, if Country2 then City2 and so on. how can i sort this, anyone knows? thanks

推荐答案

SELECT DISTINCT CityName FROM City where CountryName =@CountryName 

使用where子句更改select语句,然后可以使用 this设置参数值。 country.SelectedValue

Change the select statement with where clause as above,then you can set the parameter value using this.country.SelectedValue

您可以在第一个组合框选择的索引更改事件上加载第二个组合框。在第一个组合框选择的索引更改事件内调用 City(),其中条件根据国家/地区过滤城市

You can load the second combobox on first combobox selelected index changed event. Call the City() inside first combobox selected index changed event with the where condition to filter city based on country

相关代码的几个链接:

c#在SqlDataAdapter中使用Parameters.AddWithValue

使用C#在Windows应用程序中级联ComboBox

这篇关于彼此基于SQL C#的组合框填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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