0

我想使用 Form1 中的 comboBox1 并在表单 2 中单击按钮后将其显示在 MessageBox 中。在 Form2 中,我使用了:

    MessageBox.Show(Form.comboBox1.SelectedItem.ToString());

我收到一条错误消息,提示由于保护级别,comboBox1 无法访问。有没有办法让它公开?我还尝试将 comboBox1.SelectedItem.ToString() 分配给 Form1 中的字符串变量,并在 Form2 的 MessageBox 中使用它,但它似乎也不起作用。有没有其他方法可以让它工作?

这是我的其余代码:

    public Form1()
    {
        InitializeComponent();

        for (int i = 1; i <= 30; i++)
        {
            string[] numbers= { i.ToString() };
            comboBox1.Items.AddRange(numbers);
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 Form = new Form2();
        Form.Show();
    }
}

表格2:

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 Form = new Form1();
        MessageBox.Show(Form.comboBox1.SelectedItem.ToString()); //Here is my error
    }
}

}

4

3 回答 3

0

一种方法是这样做:

Form1你内部实例化Form2这样的 new Form2(this),即你正在传递它Form1本身,因此你应该能够使用 in 的任何公共变量/Form1属性Form2

一种更可取的方法是将selecteditemof存储Form1在一些global scope您可以访问它的地方Form2

于 2013-08-17T23:56:20.273 回答
0

Simple answer: In the designer, every control has a property called Modifiers, where you set if it's private, public, etc. Just change it and it will become visible outside of your form.

Now, in your code for Form2, you're creating a new Form1, not just accessing the previous instance that created Form2 to begin with. That will show the user a second Form1 which I guess is not what you wanted to do. The most naive way to workaround this would be to provide Form2 with a public property that will hold the Form1 which created it, and use that to access the combo:

public partial class Form2 : Form
{
    public Form1 ParentForm {get; set;}

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(this.ParentForm.comboBox1.SelectedItem.ToString());
    }
}

In Form1:

private void button1_Click(object sender, EventArgs e)
{
    Form2 form = new Form2();
    form.ParentForm = this;
    form.Show();
}
于 2013-08-18T01:36:26.893 回答
0

您可以使 ComboBox 成为如下形式的属性:

public partial class Form1 : Form
{
    public ComboBox Combo1 { get { return this.comboBox1; } }
   ...
}

然后它会起作用。但是,您必须稍微调整您的代码,因为您需要 1) 显示表单和 2) ComboBox 将立即没有选择任何内容,因此您将获得另一个异常,因此您可以强制选择。所有代码如下所示:

private void button1_Click(object sender, EventArgs e)
{

    Form1 Form = new Form1();
    Form.Show();
    Form.Combo1.SelectedIndex = 0;
    MessageBox.Show(Form.Combo1.SelectedItem.ToString()); //Here is my error
}
于 2013-08-18T00:08:42.550 回答