C# What does setting the SelectedIndex of a combobox to -1 do?

86 Views Asked by At

When I was working on one of my projects I was trying to write to a datasourced combobox and then write a value into the combobox like below:

//Create list for combobox
List<string> companyList= new List<string>() { "", "Company1", "Company2" };
//Datsource list to combobox
cbCompanyName.DataSource = companyList;

//If form is set to import data and the billing address is not null
if (importAddress && StaticValues.billAddress != null)
{
    //Fill all fields with data from Static Values class
    cbCompanyName.Text = StaticValues.billAddress.CompanyName;
    cbCountry.Text = StaticValues.billAddress.Country;
}
else
{
    //Set country to US
    cbCountry.SelectedIndex = 0;
}

however the line cbCompanyName.Text = StaticValues.billAddress.CompanyName; ran without writing any text to the combobox, until I set the selected index of the combobox to -1. What does setting the combobox selected index to -1 do that would change this as apposed to setting the selected index to 0?

2

There are 2 best solutions below

0
Russ On BEST ANSWER

Setting the SelectedIndex on a ComboBox to -1 deselects (SelectedItem is NULL). Setting to 0 selects the first item in Items

0
Çahatay özdemir On

Combobox needs to know what is my value and display member, giving the datasource is not enough for it.

I think you can use like this or

  //  comboBox.DisplayMember = "Text";
  //  comboBox.ValueMember = "Value";
int =0;
companyList.forEach(x=> comboBox.Items.Add(new { Text = x.toString(), Value =i++  })); 
comboBox1.SelectedIndex = 0;

you can look this article

similar question and answers