简体   繁体   中英

How to populate a combo box from another combo box in the same form?

Two comboBox and a table called MAINCATE is created.

I have a code , but stuck to determine what SQLQuery should i use to get the second combo box filled , determined by the first combo box.

I just need a little help on how to fill in the second combobox based on mainCate picked by the first combobox..

i need to do something like.. if combobox 1 mainCate is "Food" , then combo box 2 should show "Raw , cooked , fruits and vegetables"

This is what is inside of the MAINCATE table - ( http://i.imgur.com/qR90Z2B.png )

And this is my code :-

DataSet ds1;
DataSet ds2;

public User()
{
    InitializeComponent();
}

private void User_Load(object sender, EventArgs e)
{

    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
    conn.Open();

    SqlDataAdapter daMain = new SqlDataAdapter("SELECT * FROM MAINCATE", conn);
    ds1 = new DataSet();
    daMain.Fill(ds1, "Maincate");
    mainCatU.DisplayMember = "mainCate";
    mainCatU.ValueMember = "mainCate";
    mainCatU.DataSource = ds1.Tables["MAINCATE"];
    mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
    mainCatU.Enabled = true;

    SqlDataAdapter daSub = new SqlDataAdapter("SELECT >What should i do here?<", conn);
    ds2 = new DataSet();
    daSub.Fill(ds2, "Subcate");
    subCatU.DisplayMember = "Subcat1";
    subCatU.ValueMember = "Subcat";
    subCatU.DataSource = ds2.Tables["MAINCATE"];
    subCatU.DropDownStyle = ComboBoxStyle.DropDownList;
    subCatU.Enabled = true;
    conn.Close();
}

private void mainCatU_SelectionChangeCommitted(object sender, EventArgs e)
{
    //have no idea if a code should be here..
}

or should i do something like this?

SqlCommand cmd = new SqlCommand("select Subcat1,Subcat2,Subcat3,Subcat4 from MAINCATE where mainCate=@mainCate;", con);

=========================================

@philip - putting this on page load repalcing my code above - it didnt work..

string result = mainCatU.SelectedItem.ToString();

            SqlDataAdapter daSub = new SqlDataAdapter("SELECT * FROM MAINCATE where mainCate = " + result , conn);
            ds2 = new DataSet();
            daSub.Fill(ds2, "Subcate");
            subCatU.DisplayMember = "Subcat1";
            subCatU.ValueMember = "Subcat1";
            subCatU.DataSource = ds1.Tables["MAINCATE"];
            subCatU.DropDownStyle = ComboBoxStyle.DropDownList;
            subCatU.Enabled = true;

even tried

SqlDataAdapter daSub = new SqlDataAdapter("SELECT * FROM MAINCATE where mainCate=@result", conn);

I think this is what your looking for:

Fill the first combo box with your current code.

Then to fill the second combo box you need to hook up the first combo box selectionchangecommitted. However why not just use the standard event?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Here use if statements to capture what value is set
        if (comboBox1.SelectedIndex = 1)
        //If selected value is Vehicles
        {
            //Then SELECT * FROM MainCate WHERE MainCate = 'Vehicles'
            //This is possibly incorrect as I don't know how your DBTable is structured

            //Same code as before
            //Set this data to the second combobox
        }
    }

OK? So look into implementing this, if you want to refactor this you could, rather than using IF statements you could parametrise -

 string result = comboBox1.SelectedItem.ToString();

 SELECT * FROM MainCate WHERE MainCate = result

Obviously this won't compile so don't copy then paste it, then come back saying it doesn't work. It needs to be implemented like you did before, but rather than hardcode the result each time, use the parameter.

Personally I wouldn't have this all in one class, however you may prefer this way.

Actually, you don't need another sql query,because you already get all maincate records from database.You can simply use dictionary to store this records.

First define a Dictionary<string,List<string>>

Define it here(!)

 DataSet ds1;
 DataSet ds2;
 Dictionary<string,List<string>> allRecords = new Dictionary<string,List<string>>();

Then: (i edit your code)

SqlDataAdapter daMain = new SqlDataAdapter("SELECT * FROM MAINCATE", conn);
ds1 = new DataSet();
daMain.Fill(ds1, "Maincate");

DataTable dt = ds1.Tables["MAINCATE"];
foreach (DataRow dr in dt.Rows)
{
   List<string> SubCats = new List<string> {
     dr["Subcat1"].ToString(), 
     dr["Subcat2"].ToString(),
     dr["Subcat3"].ToString(),
     dr["Subcat4"].ToString()
   };
 allRecords.Add(dr["mainCate"].ToString(),SubCats);
 mainCatU.Items.Add(dr["mainCate"].ToString());
}

mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;

Then you need to handle mainCatU selectionchanged like this:

if(allRecords.ContainsKey(mainCatU.SelectedItem.ToString())) {
    subCatU.DataSource = allRecords[mainCatU.SelectedItem.ToString()];
}

ComboBox1, ComboBox2 -- you just want to populate ComboBox2 using ComboBox1 Select change. So, At first bind your ComboBox1. Then cretae an event for ComboBox1:

 private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
                {
                    string value1 = ComboBox1 .SelectedValue.ToString();
                    LoadComboBox2 ();        
                }

And Get your ComboBox1 selected value and use it to populate ComboBox2 .

private void LoadComboBox2 ()
        {
            DataRow dr;

            SqlConnection con = new SqlConnection(@"Data Source=name;Initial Catalog=dbName;User ID=sa;Password=sa123");
            con.Open();
            SqlCommand cmd = new SqlCommand("select id,name from table where id=@ID", con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            dr = dt.NewRow();
            dr.ItemArray = new object[] { 0, "--Select--" };
            dt.Rows.InsertAt(dr, 0);

            ComboBox2 .ValueMember = "ID";

            ComboBox2 .DisplayMember = "Name";
            ComboBox2 .DataSource = dt;
            con.Close();

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM