C#将组合框的SelectedIndex设置为-1有什么作用?
当我在我的一个项目中工作时,我试图写入一个数据源组合框,然后向组合框中写入一个值,如下所示:C#将组合框的SelectedIndex设置为-1有什么作用?,c#,combobox,selectedindex,C#,Combobox,Selectedindex,当我在我的一个项目中工作时,我试图写入一个数据源组合框,然后向组合框中写入一个值,如下所示: //Create list for combobox List<string> companyList= new List<string>() { "", "Company1", "Company2" }; //Datsource list to combobox cbCompanyName.DataSource = c
//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;
}
//为组合框创建列表
List companyList=新列表(){“”,“Company1”,“Company2”};
//Datsource列表到组合框
cbCompanyName.DataSource=companyList;
//如果表单设置为导入数据且账单地址不为空
if(importAddress&&StaticValues.billAddress!=null)
{
//用静态值类中的数据填充所有字段
cbCompanyName.Text=StaticValues.billAddress.CompanyName;
cbCountry.Text=StaticValues.billAddress.Country;
}
其他的
{
//把国家交给我们
cbCountry.SelectedIndex=0;
}
但是,行
cbCompanyName.Text=StaticValues.billAddress.CompanyName代码>运行时没有向组合框写入任何文本,直到我将组合框的选定索引设置为-1。将组合框的选定索引设置为-1会改变什么,这与将选定索引设置为0类似?将组合框上的SelectedIndex设置为-1会取消选择(SelectedItem为空)。设置为0将选择项目中的第一个项目,Combobox需要知道我的值和显示成员,
仅提供数据源是不够的
我想你可以这样或那样使用
// comboBox.DisplayMember = "Text";
// comboBox.ValueMember = "Value";
int =0;
companyList.forEach(x=> comboBox.Items.Add(new { Text = x.toString(), Value =i++ }));
comboBox1.SelectedIndex = 0;
你可以看看这篇文章