C# combobox options dependent on another combobox

这一生的挚爱 提交于 2019-12-14 00:43:06

问题


I am working on a program in which a combobox's options are dependent on another combobox's selected option. The selected item from the first combobox chooses which options are in the second combobox. Does anyone know how to do this?

This is the button that adds the information to the first 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);
        }

And here is the selectedIndex for the first combobox.

 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:


Add a SelectedIndexChanged event handler for the first ComboBox. Use it to clear the content of the second ComboBox and populate it with the related items:

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


来源:https://stackoverflow.com/questions/10239392/c-sharp-combobox-options-dependent-on-another-combobox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!