C# WinForms - filtering one combobox based on the value of another combobox in a databound datagridview

后端 未结 4 1707
我在风中等你
我在风中等你 2021-01-23 00:55

I have 4 tables - Agents, Customers, Counties and Towns. Agents and Customers both have a Town field and a County field. I have a DataGridView for each table. These are working

4条回答
  •  终归单人心
    2021-01-23 01:25

    This is my new answer. It turns out I read the question wrong (sorry about that). In my example I am using an OleDb connection to an Access Database. This is a code snippet from an app that I am currently using (names of comboboxes and tables have been changed for the example). All it does is query the database whenever the selection is changed on comboBox1 and add the result to comboBox2.

                private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //Open connection to database...
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query1 = "select * from Your_Table where Title='" + comboBox1.Text + "'";
                command.CommandText = query1;
    
                OleDbDataReader reader1 = command.ExecuteReader();
                while (reader1.Read())
                {
                    comboBox2.Items.Add(reader1["ColumnName"].ToString());
                }
                connection.Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error " + ex);
            }
        }
    

    This will query your database based on comboBox1 and put the results in comboBox2 based on your selection.

    Hope this helps!

提交回复
热议问题