1
votes

I have a problem with my code. It correctly shows the content of a combobox but whenever the data is empty it won't return to empty for example.

my 1st combobox is the clients name, after I clicked the clients name which is in a combobox connected to a database it should put his gender in a combobox.

*note this is an edit form so what I'm gonna do is to update

It is correct if the field has input, however if its not the value stored in the combobox is not changed if that field is empty

for example:

choose client 1 *show his gender in a combobox (ex. female) choose client 2 * gender is female WTF? (given that the user forgot to put his gender)

***so my problem is that if the field is empty my combobox won't be null but instead, it retains the value of the previous value that I used.

here's my code. **combobox1 is the list of the clients names, combobox2 is the gender list

private void BindControls() // function to bind the database to the comboBox
        {
           comboBox1.DataSource = _db.Client();
           comboBox1.DisplayMember = "client"; //client names are shown in the combobox
        }


 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
          comboBox2.SelectedItem =    ((DataRowView)comboBox1.SelectedItem).Row["gender"].ToString(); //the value of gender in database is put in the combobox2
        }

@@The items in my Gender combobox (combobox2) are not binded to the databse I just manually put the values there in the items properties of the combobox (which is a feature in visual studio)

Thank You Very Much! Just ask me if It is not clear to you and I'll add some details.

1

1 Answers

2
votes

Try to use something like:

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
      String genderString = ((DataRowView)comboBox1.SelectedItem).Row["gender"].ToString();

      if (!String.IsNullOrEmpty(genderString))
      {
           comboBox2.SelectedItem = ((DataRowView)comboBox1.SelectedItem).Row["gender"].ToString(); //the value of gender in database is put in the combobox2
      }
      else
      {
           comboBox2.SelectedIndex = -1;
      }
 }

It just sets the combo box back to unselected state if gender is an empty String (I suspect that null values should not appear as this column's value).