combobox population based on each other sql c#

我只是一个虾纸丫 提交于 2020-01-07 03:26:13

问题


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

T A B L E S

Country

PK CountryName

City

PK CityName

FK CountryName

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


回答1:


SELECT DISTINCT CityName FROM City where CountryName =@CountryName 

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

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

few links for related code:

c# Using Parameters.AddWithValue in SqlDataAdapter

Cascading ComboBox In Windows Application Using C#



来源:https://stackoverflow.com/questions/41188888/combobox-population-based-on-each-other-sql-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!