Search code examples
c#winformscomboboxselectedindex

Trouble setting combobox selectedindex from another form


I am trying to set the selectedindex on another form (form2) based on the user selected index on the first form (form1).

I am getting the value with this code but it returns a negative number.

public int SelectedComboIndex
{
   get { return comboBox1.SelectedIndex; }
}

And I am trying to set the comboBox Index by

comboBox1.SelectedIndex = form1.SelectedComboIndex;

Can anyone point me in the right direction as to how to do this?

Edit: More code for where its calling the code on form1

Form1 form1 = null;
public Form2(Form1 parentForm1) : this()
{
    form1 = parentForm1;
}

Solution

  • Best practice is to usually leave any sort of UI alterations in the Load method of the form, that way the form has a chance to initialize properly and all bindings are setup before you actually make changes. The Constructors should only be used to set internal state.

    private Form1 _parentForm;
    public Form2(Form1 parentForm) : this()
    {
        _parentForm = parentForm;
    }
    
    public Form2()
    {
        InitializeComponents();
    }
    
    private void Form2_Load(object sender, EventArgs e)
    {
        richTextBox1.Font = new Font("Times New Roman", 12f, FontStyle.Regular); 
        dropdown(); 
        if(_parentForm != null)
            comboBox1.SelectedIndex = _parentForm.SelectedComboIndex; 
        comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; 
    }
    

    Try that out and see if it works. Just be sure to add the Load handler to the form properly (either through the designer or in code via this.Load += new EventHandler(Form2_Load)