简体   繁体   中英

ComboBox doesn't load blank value when using ComboBox.SelectedItem = -1

I have a comboBox which correctly loads the List of data that I've queried from the DB, my only issue is that I can't seem to make it load blank and force the user to select from the list (which then pushes the actions under the SelectedIndexChanged() method). Through my searches, I've seen where I can simply change the SelectedItem value to -1, and that should load the comboBox on a null choice, but when I use this code I see no difference. The comboBox still loads the list correctly, but the first entry in the list is still displayed.

private void loadPatientList()
    {
        comboBox_PatientSelect.DataSource = patientList.Distinct().ToList();
        comboBox_PatientSelect.DisplayMember = "displayFullName";
        comboBox_PatientSelect.ValueMember = "patientID";
        comboBox_PatientSelect.SelectedItem = -1;
    }

I appreciate any help - and will be happy to provide more information if needed. Thank you in advance!

The property you're looking for is SelectedIndex . So make it comboBox_PatientSelect.SelectedIndex = -1;

From MSDN:

This property indicates the zero-based index of the currently selected item in the combo box list. Setting new index raises the SelectedIndexChanged event.

SelectedIndex, SelectedValue, and FormattingEnabled are related as follows:

  • If FormattingEnabled is false , SelectedIndex will not be set to -1 when SelectedValue is blank.
  • If FormattingEnabled is true , SelectedIndex will be set to -1 when SelectedValue is blank.

NOTE:

To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item.

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