class ComboBoxCompany
{
public string Code;
public string Name;
public string Database;
public ComboBoxCompany(string code, string name, string database)
{
Code = code; Name = name; Database = database;
}
public override string ToString()
{
// Generates the text shown in the combo box
return Name;
}
}
class ComboBoxDatabase
{
public string cmpName;
public string dbName;
public ComboBoxDatabase(string cmpname, string dbname)
{
cmpName = cmpname; dbName = dbname;
}
public override string ToString()
{
// Generates the text shown in the combo box
return cmpName + " - " + dbName;
}
}
这些是2个组合框的类,所以当我选择第一个组合的值时(ComboBoxCompany),我希望第二个组合框(ComboBoxDatabase)从第一个组合框“数据库”中选择“dbName”-Value - 值
我试过这个,但它没有
private void cbxBranch_SelectedIndexChanged(object sender, EventArgs e)
{
cbxDatabase.SelectedItem = (cbxCompany.SelectedItem as ComboBoxCompany).Database;
}
答案 0 :(得分:0)
通过设置
(cbxCompany.SelectedItem as ComboBoxCompany).Database
您尝试将所选项目设置为不存在的数据库字符串,因为您似乎添加了一个类作为组合框架。
您需要将SelectedItem设置为真实对象。您可以使用linq(示例代码)搜索此内容:
var company = cbxCompany.SelectedItem as ComboBoxCompany;
if(company == null)
return;
var dbItem = _databaseComboBoxItems.FirstOrDefault(x=>x.CompanyName = company.CompanyName && x.Database == company.DatabaseName);
if(dbItem == null)
return;
cbxDatabase.SelectedItem = dbItem;