I've been scratching my brain over the past few days on how to refresh a DataGridView. I finally found some Microsoft documentation that worked; it mentioned that I needed to remove the DataSource, re-add the DataSource, and re-fill the TableAdapter.
If I create a button on my form and add this code to the Click event, the DataGridView will refresh.
dgvApps.DataSource = null;
dgvApps.DataSource = dStblApplications.tblApplications;
tblApplicationsTableAdapter.Fill(dStblApplications.tblApplications);
However, if I place this same code within a Function in the same form as the DataGridView, but is activated from another form, it won't work. I started debugging and found that the code is reached by the compiler, and is read, but it isn't executed.
//This is on Form1. Function that is called to create a popup box asking the user if they would like to re-submit the form.
public void SaveNewApplicationEntry()
{
string message = $"Successfully Created \n Would you like to create another application?";
string title = "Confirmation Required";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult displayMsg = MessageBox.Show(message, title, buttons);
if (displayMsg == DialogResult.Yes)
{
addAppForm.Close();
frmAddApplication addNewApp = new frmAddApplication();
addNewApp.Show();
}
else
{
dgvApps.DataSource = null;
dgvApps.DataSource = dStblApplications.tblApplications;
tblApplicationsTableAdapter.Fill(dStblApplications.tblApplications);
addAppForm.Close();
}
//This is on Form2
private void btnSubmit_Click(object sender, EventArgs e)
{
newApp.AppName = txtAppName.Text;
newApp.AppDescription = txtAppDescription.Text;
newApp.AppMasterLocation = txtAppMasterLoc.Text;
newApp.AppCurrentVersion = txtAppCurrentVer.Text;
newApp.ActiveDate = dtpAppActiveDate.Value == null ? DateTime.Now : dtpAppActiveDate.Value;
newApp.InactiveDate = dtpAppInactiveDate.Value == null ? DateTime.Now : dtpAppInactiveDate.Value;
if (!newApp.AppName.Equals("") && !newApp.AppDescription.Equals("") && !newApp.AppMasterLocation.Equals("") && !newApp.AppCurrentVersion.Equals(""))
{
frmApplications mainApplicationForm = new frmApplications();
mainApplicationForm.SaveNewApplicationEntry();
}
}
Is there a proper way to refresh a DataGridView on Form1 from within Form2?
You face the problem because of this code :
frmApplications mainApplicationForm = new frmApplications();
mainApplicationForm.SaveNewApplicationEntry();
Your problem is that you are creating an instance of frmApplication, So the SaveNewApplicationEntry() in the opened form isn't called.
You can try this instead :
if (Application.OpenForms.Cast<Form>().Any(form => form.Name == "frmApplications"))
{
frmApplications frmApp = (frmApplications)Application.OpenForms["frmApplications"];
frmApp.SaveNewApplicationEntry();
}