Fill in the combo box depending on another combobox

im creating wpf where one combobox is populated depending on another combobox. however, only one group is filled.

this is my code below.

public partial class Form4 : Form { public Form4() { InitializeComponent(); this.Load += Form4_Load; } string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;"); private void Form4_Load(object sender, EventArgs e) { string query = "SELECT * FROM data_organsystem"; fillCombo(comboBox3, query, "name", "id"); comboBox3_SelectedIndexChanged(null, null); } private void fillCombo(ComboBox combo, string query, string displayMember, string valueMember) { NpgsqlConnection conn = new NpgsqlConnection(connstring); NpgsqlCommand cmd = new NpgsqlCommand(query, conn); NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); combo.DataSource = dt; combo.DisplayMember = displayMember; combo.ValueMember = valueMember; } private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) { int val; Int32.TryParse(comboBox3.SelectedValue.ToString(), out val); string query = "SELECT * FROM data_symptom WHERE organ_system_id = " + val; fillCombo(comboBox4, query, "name", "id"); } } } 

If you have an idea on editing this code, this will be a big help. thanks!

+4
source share
2 answers

You never add comboBox4 to your form. comboBox3 is added through the constructor, but comboBox4 is created and added to nowhere.

0
source

You will get an error when executing the comboBox3_SelectedIndexChanged method on a line

 Int32.TryParse(comboBox3.SelectedValue.ToString(), out val); 

Since comboBox3.SelectedValue is null if no element was selected in the ComboBox element, I did not see in your code that you selected some elements before calling comboBox3_SelectedIndexChanged for the first time.

Because the comboBox3_SelectedIndexChanged method executed inside Form.Load , an event handler exception was not shown. Check this out: fooobar.com/questions/392916 / ....
That's why you didn’t get any errors

You need to check SelectedValue for null before using it

 If(this.comboBox3.SelectedValue is null) { this.comboBox4.DataSource = null; //Remove all items if nothing selected } else { Int32 val= (Int32)this.ComboBox3.SelectedValue; string query = "SELECT id, name FROM data_symptom WHERE organ_system_id = " + val; fillCombo(this.comboBox4, query, "name", "id"); } 

Since you use a DataBinding when populating a ComboBox elements, it is logical to use the SelectedValueChanged event handler

 private void comboBox3_SelectedValueChanged(object sender, EventsArgs e) { //same code } 
0
source

All Articles