I made an application that displays some data in a DataGridView control. The data is stored in an SQL database. Since there are a lot of parameters for this specific display, I created another (child) form in the same project that helps the user to add or alternate the data in the database. Both adding and alternating functions work fine, but the data in the DataGridView stays unchanged. I know how to refresh the DataGridView’s DataSource, but I don’t know how to trigger that function form another form.
I use this function to refresh the DataGridView’s DataSource:
private void RefreshMyDGV()
{
command.CommandText = "SELECT * FROM MyDataBase";
SDA.SelectCommand = command;
SDA.Fill(myDataTable);
dataGridView1.DataSource = MyDataTable;
}
I tried to change this function into a public static function so I would be able to access it from the other (child) form, but then the compiler throws errors “An object reference is required for the non-static field, method, or property”.
I also tried to define the DataGridView as public, and then access it from the other form:
((Form1)fr1).dataGridView1.DataSource = myDataTable;
But that didn’t work either.
Please suggest a way to do this.
Thanks.
The issue is that you are making the function
static. You don’t need to do that – just make itpublic.See this documentation on the difference between static and instance methods:
http://msdn.microsoft.com/en-us/library/aa645629(v=vs.71).aspx
In order to call a public function, you will need a reference to the parent form instance (not just the class) from your child form. Add a property to your child form called
LogicalParentof typeParentForm(substitute your actual parent form’s type) (there’s already properties namedParentandParentForm, but they’re used for something else and you should not use them):Now, on the parent form, when you open a new instance of the child form, set this property just before calling the Show function:
Now, on the child form, you have a reference to the parent. You can now call public functions:
Alternative:
On the parent form, pass a reference to the parent form to the
ShowDialogfunction:Now, on the child window, you can access the parent form via the
Ownerproperty. But you will need to cast theOwnerproperty to you parent form’s type. So, in the child form:MDI:
If you are using an MDI environment (ignore this if you don’t know what that is), then you can use the
ParentFormproperty in the same way that you used theOwnerproperty above (you will need to cast it to the parent’s type). MDI environment are more complicated to explain, and since you haven’t said that’s what you are using I won’t explain it here. If you need more information, visit: http://msdn.microsoft.com/en-us/library/xyhh2e7e.aspx