如何更新由另一个组合框触发的组合框中的值? [英] How to update the values in a combobox triggered by another combobox?

查看:73
本文介绍了如何更新由另一个组合框触发的组合框中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个表单组合框。

我希望在combobox2中的列表更新时更改combobox1中的选定值。

I'd like the selected value in combobox1 to change when the list in combobox2 gets updated.

例如:ComboBox1具有移动公司的名称,而ComboBox2具有该公司所有手机的列表。

For Example: ComboBox1 has names of mobile companies and ComboBox2 containing the list of all mobile phones of that company.

推荐答案

假设您有一本将手机型号与其制造商相关联的字典:

Assume you have a dictionary that associates phone models to their manufacturers:

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

您可以将要显示在左侧组合框中的项目显示为:

You can get the items to be displayed in the left combo box as:

foreach (string brand in brandsAndModels.Keys)
    comboBox1.Items.Add(brand);

您只能执行一次,例如在表单的 Load 事件。注意: brandsAndModels 词典必须是一个实例变量,而不是局部变量,因为我们以后需要访问它。

You do this only once, for example in the form's Load event. Note: The brandsAndModels dictionary must be an instance variable, not a local variable as we need to access it later on.

然后,您必须为 SelectedIndexChanged 事件分配一个事件处理程序,在该事件处理程序中,将第二个组合框中的项目替换为数组中的项目。选定品牌:

Then, you'd have to assign an event handler for the SelectedIndexChanged event, in which you replace the items in the second combo box with the items in the array for the selected brand:

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]);
    }
}

如果所有这些都来自数据库,如我在评论中链接到您的问题的问题的答案中所述,使用数据绑定会更好。

If all of this came from a database, things would be much nicer using data bindings as described in the answers to the question I've linked in my comment to your question.

这篇关于如何更新由另一个组合框触发的组合框中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆