【发布时间】:2012-12-19 14:00:46
【问题描述】:
我在一个表单中有 2 个组合框。
我希望在combobox2 中的列表更新时更改combobox1 中的选定值。
例如:ComboBox1 包含移动公司的名称,ComboBox2 包含该公司所有手机的列表。
【问题讨论】:
我在一个表单中有 2 个组合框。
我希望在combobox2 中的列表更新时更改combobox1 中的选定值。
例如:ComboBox1 包含移动公司的名称,ComboBox2 包含该公司所有手机的列表。
【问题讨论】:
假设您有一本将手机型号与其制造商相关联的字典:
Dictionary<string, string[]> brandsAndModels = new Dictionary<string, string[]>();
public void Form_Load(object sender, EventArgs e)
{
brandsAndModels["Samsung"] = new string[] { "Galaxy S", "Galaxy SII", "Galaxy SIII" };
brandsAndModels["HTC"] = new string[] { "Hero", "Desire HD" };
}
你可以得到要在左侧组合框中显示的项目:
foreach (string brand in brandsAndModels.Keys)
comboBox1.Items.Add(brand);
您只需执行一次此操作,例如在表单的 Load 事件中。注意:brandsAndModels 字典必须是实例变量,而不是局部变量,因为我们稍后需要访问它。
然后,您必须为 SelectedIndexChanged 事件分配一个事件处理程序,在其中您将第二个组合框中的项目替换为所选品牌的数组中的项目:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Items.Clear();
if (comboBox1.SelectedIndex > -1)
{
string brand = brandsAndModels.Keys.ElementAt(comboBox1.SelectedIndex);
comboBox2.Items.AddRange(brandsAndModels[brand]);
}
}
如果所有这些都来自数据库,那么使用数据绑定会更好,如我在评论中链接到您的问题的问题的答案中所述。
【讨论】:
st2) 分配 到组合框 Items 集合中。但是,您可以使用AddRange 方法。我将更新我的代码,因为这实际上是一种简化。
comboBox1 中的项目进行排序怎么办?然后你需要在中间插入另一个品牌吗?您想每次都更新if 语句吗?例如:假设您现在有 HTC 和 Samsung。明天你需要插入 LG。使用我的方法没问题 - 使用你的方法做了大量工作,因为你需要更新所有 ifs。
您必须处理组合框的SelectedIndexChanged 事件才能实现该目标
【讨论】:
当您看起来很新时,我将逐步向您解释。
你可以在此之后使用以下代码。
Dictionary<string, string[]> models = new Dictionary<string, string[]>();
public Form1()
{
InitializeComponent();
//initializing combobox1
comboBox1.Items.Add("Select Company");
comboBox1.Items.Add("HTC");
comboBox1.Items.Add("Nokia");
comboBox1.Items.Add("Sony");
//select the selected index of combobox1
comboBox1.SelectedIndex = 0;
//initializing model list for each brand
models["Sony"] = new string[] { "Xperia S", "Xperia U", "Xperia P" };
models["HTC"] = new string[] { "WildFire", "Desire HD" };
models["Nokia"] = new string[] { "N97", "N97 Mini" };
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Items.Clear();
if (comboBox1.SelectedIndex > -1)
{
string brand = comboBox1.SelectedItem.ToString();
if(brand != "" && comboBox1.SelectedIndex > 0)
foreach (string model in models[brand])
comboBox2.Items.Add(model);
}
}
【讨论】:
Dictionary<string, string[]> models = new Dictionary<string, string[]>();吗?
0 = Select Company 或1 = HTC 或2 = Nokia 或3 = Sony
Breakpoint 与Visual Studios 一起使用,看看代码是如何工作的以及即将到来的值。