C#组合框选项依赖于另一个组合框

时间:2012-04-20 02:20:14

标签: c# combobox

我正在开发一个程序,其中组合框的选项依赖于另一个组合框的选定选项。第一个组合框中的所选项目选择第二个组合框中的哪些选项。有谁知道怎么做?

这是将信息添加到第一个组合框

的按钮
    try
        {
            CustomerAccount aCustomerAccount = new CustomerAccount(txtAccountNumber.Text, txtCustomerName.Text,
            txtCustomerAddress.Text, txtPhoneNumber.Text);
            account.Add(aCustomerAccount);

            cboClients.Items.Add(aCustomerAccount.GetCustomerName());
            ClearText();
        }
        catch (Exception)
        {
            MessageBox.Show("Make sure every text box is filled in!", "Error", MessageBoxButtons.OK);
        }

这是第一个组合框的selectedIndex。

 private void cboClients_SelectedIndexChanged(object sender, EventArgs e)
    {

        CustomerAccount custAccount = account[cboClients.SelectedIndex] as CustomerAccount;
        if (custAccount != null)
        {
            txtAccountNumberTab2.Text = custAccount.GetAccountNumber();
            txtCustomerNameTab2.Text = custAccount.GetCustomerName();
            txtCustomerAddressTab2.Text = custAccount.GetCustomerAddress();
            txtCustomerPhoneNumberTab2.Text = custAccount.GetCustomerPhoneNo();
        }
    }

1 个答案:

答案 0 :(得分:6)

为第一个SelectedIndexChanged添加ComboBox事件处理程序。使用它来清除第二个ComboBox的内容并使用相关项填充它:

public Form1()
  {
    InitializeComponent();
    for(int i = 0; i < 10; i++) {
        comboBox1.Items.Add(String.Format("Item {0}", i.ToString()));
    }
    comboBox1.SelectedIndex = 0;
  }

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  {
    comboBox2.Items.Clear();
    for (int i = 0; i < 5; i++)
    {
      comboBox2.Items.Add(String.Format("Item_{0}_{1}", 
                          comboBox1.SelectedItem, i.ToString()));
    }
    comboBox2.SelectedIndex = 0;
  }