1rx 1rx - 2 months ago 10
C# Question

Calling method in parent form from child form to reload datagridview rows in parent form

I have a parent form and a child form.

There is a data grid view element,

dgv
, in the parent form.

Rows are added to this
dgv
when the parent form is loaded.

Data to create the rows are obtained from MySQL database.

Button on the parent form loads a child form.

Child form alters the DB table content and then calls the parent method in order to reload the
dgv
so the user sees the changes done and then closes the child form.

Child form calling the parent method:

parentForm obj_parentform = new parentForm();
obj_parentform.loadGrid("from_child");


There is a another button in the parent form I created for debugging purposes which calls a local method as it is in the same form.

private void btn_debug_Click(object sender, EventArgs e) {
this.loadGrid("btn");
}


Method:

public void loadGrid(string caller) {
try {
this.dgv.Rows.Clear();
Console.WriteLine("### - caller: " + caller);

string link = "database;datasource;port;username;password";

MySqlConnection conn = new MySqlConnection(link);
String query = "SELECT * FROM table";
MySqlCommand cmd = new MySqlCommand(query, conn);
conn.Open();
MySqlDataReader dr = cmd.ExecuteReader();

if(dr.HasRows) {
while(dr.Read()) {
this.dgv.Rows.Add(
Convert.ToString(dr.GetValue(0)),
Convert.ToString(dr.GetValue(1)),
Convert.ToString(dr.GetValue(2)),
Convert.ToString(dr.GetValue(3)),
Convert.ToString(dr.GetValue(4))
);
}
}

cmd.Dispose();
conn.Close();

}catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}


Now when the child form alters data in the table, and it calls the parent method, I can see the console showing:

### - caller: from_child


but the
dgv
shows the same rows, no change is done even when the method is entered.

After that, I press the debug button, and console shows:

### - caller: btn


and the
dgv
is reloaded and changes previously done from child form are now shown.

Both calls are entering the method but why is
dgv
only loading data when method is accessed from debug
btn
?

1rx 1rx
Answer

I solved this issue. I needed to pass some reference to the parent form at the moment I created the child form.

Since I was creating a new parentForm object to access its methods, this new object was not the already instanciated parent form object, that's why it wasn't working.

This is the code:

At the parent form:

frm_childForm obj_childForm = new frm_childForm(this);
obj_childForm.ShowDialog();

At the child form:

Create property to hold the reference to its parent:

private parentForm obj_parentform = null;

Set reference to parent form in constructor:

public frm_finalizarTurno(parentForm parent) {
    obj_parentform = parent;
}

Now lets call parent method from within child form:

obj_parentform.loadGrid("child");