首页 > 解决方案 > C# 将组合框的 SelectedIndex 设置为 -1 有什么作用?

问题描述

当我在处理我的一个项目时,我试图写入数据源组合框,然后将值写入组合框,如下所示:

//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;
}

但是该行在cbCompanyName.Text = StaticValues.billAddress.CompanyName;没有向组合框写入任何文本的情况下运行,直到我将组合框的选定索引设置为-1。将组合框选定索引设置为 -1 会改变这一点,而不是将选定索引设置为 0?

标签: c#comboboxselectedindex

解决方案


将 ComboBox 上的 SelectedIndex 设置为 -1 会取消选择(SelectedItem 为 NULL)。设置为 0 选择 Items 中的第一项


推荐阅读