【问题标题】:combobox population based on each other sql c#基于彼此的组合框填充sql c#
【发布时间】:2016-12-17 00:59:58
【问题描述】:

我有 2 个盒子,我想从 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 国名

城市

PK 城市名

FK 国家/地区名称

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

【问题讨论】:

    标签: c# sql combobox


    【解决方案1】:
    SELECT DISTINCT CityName FROM City where CountryName =@CountryName 
    

    如上用where子句改变select语句,即可使用this.country.SelectedValue设置参数值

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

    相关代码的几个链接:

    c# Using Parameters.AddWithValue in SqlDataAdapter

    Cascading ComboBox In Windows Application Using C#

    【讨论】:

    • 谢谢。目前没有时间测试它,但如果有效,绝对会做并标记答案为好!
    • @mihocu 希望你理解这个概念,给定的链接将帮助你自己编写代码。
    猜你喜欢
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2012-11-24
    • 2012-02-29
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多