views:

54

answers:

2

I'm trying to reference the selected index of a combobox on my mainform in an if statement inside a method on a second form. Some google searching has confused me a bit. The most obvious answer I can see is just making the combobox control on the mainform public, however the websites I've been reading seem to indicate that this is not the prefered method? If this is the case what is the prefered method? I've coded in the secondary constructor method on the second form to accept the first form as a parameter when called, for example:

Form2 form = new Form2(this);
form.Show();

And on the second form:

public partial class Form2 : Form
{
    Form1 form1;
    public Form2()
    {
        InitializeComponent();
    }
    public Form2(Form1 fr1)
    {
        InitializeComponent();
        form1 = new Form1();
        form1 = fr1;

So I thought I could just do something like form1.combobox1.SelectedIndex, but no dice....what is the 'community prefered' method to go about doing this?

+1  A: 

On your main form, create a public property that returns the combobox.

+1  A: 

Well you can just return SelectedIndex property of the combobox by doing something like this in Form1 class or whatever form that is containing the combobox.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public int SelectedIndex
    {
        get
        {
            return comboBox.SelectedIndex;
        }
    }

}

Then in order to call it, just continue what you were doing before

public partial class Form2 : Form
{
    Form1 form1;
    public Form2()
    {
        InitializeComponent();
    }
    public Form2(Form1 fr1)
    {
        InitializeComponent();
        // get rid of this line it's unnecessary
        // form1 = new Form1();
        form1 = fr1;
    }
}

and call the property wherever needed in your Form2 class like this form1.SelectedIndex.

Avoid this section if it's confusing, but you don't really need to create a field for Form1. Use Form's ParentForm instead and cast it to Form1 whenever needed like ((Form1)this.ParentForm).SelectedIndex

Hamid Nazari
This is just a property right? How do I refer to this property from the code on the second form?
Stev0
improved the answer. I hope it's clear this now.
Hamid Nazari
Thats exactly how I am calling it, yet its giving me the non-static error
Stev0
I don't know how you are initializing `Form2` and opening it, give me your email address here or via my contact form on my blog, and I'll send you a sample project.
Hamid Nazari
I figured out the problem. The method from which I was attempting to reference the mentioned property was defined as static. I == unobservant :)
Stev0