refresh a dataGridView from another form
Asked Answered
S

3

5

I have Form1 and Form2.

Form1 has a dataGridView and a button for opening Form2. I have written a method in Form1 as below that perfectly refreshes the 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. When I traced the code I saw that it implements all the way but the dataGridView isn't refreshed!

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.

Help me out plz!

Seigniorage answered 18/11, 2014 at 17:36 Comment(2)
Here's a link which describes how to pass an instance #4177182Somnus
@Somnus Thank u so much for leaving me that link, It made the job for me.Seigniorage
E
6

Your problem is that you're creating a new instance of Form1. Instead of new Form1 you need to pass an instance of the existing Form1 to Form2

Emden answered 18/11, 2014 at 17:38 Comment(0)
S
10

I solved my problem with the help of @MikeH and @Sybren:

Form1:

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

Form2:

    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();
    }
Seigniorage answered 18/11, 2014 at 18:25 Comment(0)
E
6

Your problem is that you're creating a new instance of Form1. Instead of new Form1 you need to pass an instance of the existing Form1 to Form2

Emden answered 18/11, 2014 at 17:38 Comment(0)
M
0

Before closing the scope of the button_click who is open the Form2 re-implement the method RefreshGrid().

Margarettamargarette answered 30/7 at 11:6 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Saleem

© 2022 - 2024 — McMap. All rights reserved.