Unable to update comboBox from another comboBox

Total Post:110

Points:774
 1690  View(s)
Ratings:
Rate this:
private void tabControl1_Selected(object sender,TabControlEventArgs e)
    {
        if(e.TabPage.Name == tabPage2.Name)
        {
            table =Items.Get();
            comboBox1.DataSource = table;
            comboBox1.DisplayMember = "Item_ID";
        }
    }
   private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable temp = new DataTable();
        string text = comboBox1.SelectedItem.ToString();
        temp = Color.Get(text);
        comboBox2.DataSource = temp;
        comboBox2.DisplayMember = "Color_Name";
        comboBox2.ValueMember = "Color_ID";
    }

I am trying to populate the comboBox1 as the tabpage open and then populate the comboBox2 based on the selectedText of comboBox1.

comboBox_SelectedIndexChange runs 2 times when tab changes but returns null every times.

Note: I have already appended event handler as the form initializes like,

public Form1()
    {
        InitializeComponent();
        tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
        comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
        table = new DataTable();
        s = new Stock();
    }
  1. Post:145

    Points:1019
    Re: Unable to update comboBox from another comboBox

    Hi Jayden,

    First there is a bug in

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable temp = new DataTable();
        string text = comboBox1.SelectedItem.ToString();
        temp = Color.Get(text);
        comboBox2.DataSource = temp;
        comboBox2.DisplayMember = "Color_Name";
        comboBox2.ValueMember = "Color_ID";
    }

    code. You override value for datasource in line

    temp = Color.Get(text);

    I think it should be like:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable temp = new DataTable();
        string text = comboBox1.SelectedItem.ToString();
        selectedColor = Color.Get(text);
        comboBox2.DataSource = temp;
        comboBox2.DisplayMember = "Color_Name";
        comboBox2.ValueMember = "Color_ID";
        comboBox2.SelectedItem = selectedColor;
    }

    I don't know contents of DataTable so instead of comboBox2.SelectedItem you may need to set SelectedItem, SelectedText or SelectedValue properties of comboBox2.

      Modified On Apr-04-2018 12:35:52 AM

Answer