开发者

Using the selected index of a combobox in an If statement of a different form

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;
    pub开发者_开发百科lic 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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜