日期:2014-05-18  浏览次数:20914 次

如何刷新另一个窗体的datagridview
form1中为某张数据表中的数据,有一个添加按钮,点击后打开form2输入新的一条数据,在form2中点击保存按钮保存后如何能刷新form1中的datagridview,使其显示出新添加的那条数据?

------解决方案--------------------
探讨
form1中为某张数据表中的数据,有一个添加按钮,点击后打开form2输入新的一条数据,在form2中点击保存按钮保存后如何能刷新form1中的datagridview,使其显示出新添加的那条数据?

------解决方案--------------------
使用invoke可以做到。详细的代码如下
要刷新的窗体Form1
C# code
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    public void renovate()
    {
      //刷新的代码
    }
  }
}

Form2的代码
C# code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        private Form1 _MyForm1 = new Form1();

        public Form1 MyForm1
        {
            get { return _MyForm1; }
            set { _MyForm1 = value; }
        }

        
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //回调Form1的刷新事件
            _MyForm1.Invoke(new Action(_MyForm1.renovate));
            //更多的操作可以看看Invoke的详细资料,也可以看看多线程之间的通信资料
        }
    }
}