简体   繁体   English

从另一种形式刷新dataGridView

[英]refresh a dataGridView from another form

I have Form1 and Form2. 我有Form1和Form2。

Form1 has a dataGridView and a button for opening Form2. Form1有一个dataGridView和一个用于打开Form2的按钮。 I have written a method in Form1 as below that perfectly refreshes the dataGridView: 我在Form1中编写了一个如下所示的方法,该方法可以完美地刷新dataGridView:

public void RefreshGrid()
    {
        dataGridView1.DataSource = empControl.SelectAll(); //Works great
    }

In Form2 I insert into the table and use the below Code for Calling the above method. 在Form2中,我插入到表中,并使用下面的代码调用上述方法。 When I traced the code I saw that it implements all the way but the dataGridView isn't refreshed! 当我跟踪代码时,我看到它完全实现了,但是dataGridView没有刷新!

private void btnInsert_Click(object sender, EventArgs e)
    {
            //Insert Code (Inserts perfectly)

            Form1 frm = new Form1();
            frm.RefreshGrid();
            this.Close();
        }
    }

I also tried the FormClosing Event of Form2 but it didn't do the trick. 我还尝试了Form2的FormClosing事件,但没有成功。

Help me out plz! 请帮帮我!

Your problem is that you're creating a new instance of Form1 . 您的问题是您正在创建Form1的新实例。 Instead of new Form1 you need to pass an instance of the existing Form1 to Form2 代替new Form1您需要将现有 Form1的实例传递给Form2

I solved my problem with the help of @MikeH and @Sybren: 我借助@MikeH和@Sybren解决了我的问题:

Form1: 表格1:

Form2 frm = new Form2(this);
frm.Show();

Form2: 表格2:

    private readonly Form1 frm1; //readonly is optional (For safety purposes)

    public Form2(Form1 frm)
    {
        InitializeComponent();

        frm1 = frm;
    }

    private void btnInsert_Click(object sender, EventArgs e)
    {
        frm1.RefreshGrid();
        this.Close();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM