Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

c# - Update a combo box automatically when first combo box gets some value

I have two combo boxes. I insert one value in first combo box and now i want that my second combo box updates its value according to first one. How should i do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Handle the SelectedIndexChanged event for the first ComboBox, then update the second combo box based on the SelectedItem value for the first ComboBox.

A quick example (sans error handling when retrieving the SelectedItem):

public partial class Form1 : Form
{
    private string[] comboBox1Range = new[] { "A", "B", "C", "D" };
    private string[] comboBox2RangeA = new[] { "A1", "A2", "A3", "A4" };
    private string[] comboBox2RangeB = new[] { "B1", "B2", "B3", "B4" };
    private string[] comboBox2RangeC = new[] { "C1", "C2", "C3", "C4" };
    private string[] comboBox2RangeD = new[] { "D1", "D2", "D3", "D4" };

    public Form1()
    {
        InitializeComponent();
        comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
        comboBox1.Items.AddRange(comboBox1Range);
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedValue = comboBox1.SelectedItem as string;

        switch (selectedValue)
        {
            case "A":
                comboBox2.Items.Clear();
                comboBox2.Items.AddRange(comboBox2RangeA);
                break;
            case "B":
                comboBox2.Items.Clear();
                comboBox2.Items.AddRange(comboBox2RangeB);
                break;
            case "C":
                comboBox2.Items.Clear();
                comboBox2.Items.AddRange(comboBox2RangeC);
                break;
            case "D":
                comboBox2.Items.Clear();
                comboBox2.Items.AddRange(comboBox2RangeD);
                break;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...