当前位置: 代码迷 >> .NET组件控件 >> 子窗体操作父窗体中数据解决方案
  详细解决方案

子窗体操作父窗体中数据解决方案

热度:160   发布时间:2016-05-04 23:27:43.0
子窗体操作父窗体中数据
主窗体 Form1代码如下 (有个ListBox控件和button控件 Click事件弹出子窗体):

  private void button1_Click(object sender, EventArgs e)
        {
            Form2 fr = new Form2(this.listBox1);
            this.Visible = false;//设置主窗体不可见
            fr.Show();//弹出子窗体
        }


子窗体代码如下(构造函数将主窗体的ListBox控件传过来了,new了一个ListBox将传递过来的给它赋上,button2按钮添加信息,button3显示主窗体):

   public partial class Form2 : Form
    {
        int i = 0;
        ListBox lis = new ListBox();
        public Form2(ListBox list)
        {
            InitializeComponent();
            this.lis = list;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //添加新数据
            this.lis.Items.Add(i);
            i++;

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //设置主窗体可见
            Form1 f = new Form1();
            f.Visible = true;
        }

问题:
将主窗体的这句话注释掉→_→(this.Visible = false;//设置主窗体不可见)
点击子窗体的button2可以往父窗体中的ListBox中添加信息,
但是不注释掉→_→(this.Visible = false;//设置主窗体不可见)这句话
点击button2添加,再点击button3按钮显示主窗体时,父窗体中的ListBox还是没变化

怎样才能让父窗体隐藏下然后点击子窗体添加信息,再点击显示主窗体,主窗体中ListBox中的数据增加?
------解决方案--------------------
原因很简单,因为Button3里面重新new了一个窗体,已经不是原来那个窗体了,所以不行。
你可以在Form1里面,把Form1自身传过去(传引用),然后在Form2的Button3里面直接设置Visible为true就可以了。
具体步骤如下:
Form1.cs修改为:
private void button1_Click(object sender, EventArgs e)
        {
            Form2 fr = new Form2(this, this.listBox1);
            this.Visible = false;//设置主窗体不可见
            fr.Show();//弹出子窗体
        }

Form2.cs修改为:
 int i = 0;
        private Form form1;
        private ListBox lis;

        public Form2(Form form1, ListBox lis)
        {
            InitializeComponent();
            this.form1 = form1;
            this.lis = lis;
        }

 private void button3_Click(object sender, EventArgs e)
        {
            //设置主窗体可见
            //Form1 f = new Form1();
            form1.Visible = true;
        }
  相关解决方案