从另一个表单调用ComboBox

时间:2014-02-20 05:20:00

标签: c# .net winforms

我有2个表单 - Form1和Form2,Form1有ComboBox,Form2属性有FormBorderStyle作为FixedToolWindow。我需要从Form2调用ComboBox,我该怎么做?

1 个答案:

答案 0 :(得分:0)

我看到问题已经改写,意思发生了重大变化。

简单的事实是,Form2甚至不应该知道ComboBox存在,甚至不知道Form1是否存在。正确的方法是Form2引发事件,Form1处理该事件。当需要发生某些事情时,Form2会引发事件,然后Form1访问它自己的ComboBox。

Check this out。第3部分解释了应该如何完成。

这是一个相对人为的例子:

Form1中:

using System;
using System.Windows.Forms;

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

        private Form2 form2Instance;

        private void button1_Click(object sender, EventArgs e)
        {
            // Check whether there is already a Form2 instance open.
            if (this.form2Instance == null || this.form2Instance.IsDisposed)
            {
                // Create a new Form2 instance and handle the appropriate event.
                this.form2Instance = new Form2();
                this.form2Instance.SelectedValueChanged += form2Instance_SelectedValueChanged;
            }

            // Make sure the Form2 instance is displayed and active.
            this.form2Instance.Show();
            this.form2Instance.Activate();
        }

        private void form2Instance_SelectedValueChanged(object sender, EventArgs e)
        {
            // Update the ComboBox based on the selection in Form2.
            this.comboBox1.SelectedIndex = this.form2Instance.SelectedValue;
        }
    }
}

窗体2:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Gets the value selected in the NumericUpDown as an int.
        /// </summary>
        public int SelectedValue { get { return Convert.ToInt32(this.numericUpDown1.Value); } }

        /// <summary>
        /// Raised when the value in the NumericUpDown changes.
        /// </summary>
        public event EventHandler SelectedValueChanged;

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            if (this.SelectedValueChanged != null)
            {
                // Notify any listeners that the selection has changed.
                this.SelectedValueChanged(this, EventArgs.Empty);
            }
        }
    }
}

如您所见,Form2根本没有对Form1的引用,因此不需要知道或关心Form1是否存在。