0

I have reload the data for data grid view each time the form open.

 Student_DetailEntities db = new Student_DetailEntities();
 private void Form1_Load(object sender, EventArgs e)
 {
     db.StudentTables.Load();
     studentTableBindingSource.DataSource = db.StudentTables.Local;
 }

To ensure the data table is refresh and show in data grid view, I have tried this code

private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
{
        Application.Restart();
        Environment.Exit(0);
}

and I try

private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
{
        this.Controls.Clear();
        this.InitializeComponent();
}
  

But the data grid view still not reload. Each time I add new item, I need to close and open the form again for it to show in data grid view.

irham dollah
  • 169
  • 13

1 Answers1

2

You can use Shown event instead of Form.Load.So that you can reload the data each time the form is shown.

Student_DetailEntities db = new Student_DetailEntities();
private void Form1_Load(object sender, EventArgs e)
{
    Shown += Form1_Shown; 
}
 
 
private void Form1_Shown(object sender, EventArgs e) 
{
     db.StudentTables.Load();
     studentTableBindingSource.DataSource = db.StudentTables.Local;
}

See the detail of Form.Load, Form.Shown:

Order of events 'Form.Load', 'Form.Shown' and 'Form.Activated' in Windows Forms

@Caius Jard pointed out in comments, you can simply add Form.Shown event handler by "Form Designer --> Properties --> Events --> double click Shown then add code" instead of Shown += Form1_Shown; in Form1_Load that I mentioned above.

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
  • You are right. I have added your suggestion as well. Thanks for contribution – Selim Yildiz Jun 26 '20 at 06:57
  • I have added the `form_1_shown` and `form_1_load` as you show above. But when I do `application.restart`, it still not reload. The data grid view still showing same result. – irham dollah Jun 26 '20 at 07:28
  • You don't need to `Application.Restart` just try to use [`ShowDialog`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.showdialog) . – Selim Yildiz Jun 26 '20 at 07:38
  • Do u mean I use `Form f = new Form(); f.ShowDialog = DialogResult.OK; ` under `refreshToolStripMenuItem_Click`? – irham dollah Jun 26 '20 at 07:57
  • It depends what you want, You can use ShowDialog as `Form f = new Form(); f.ShowDialog();` or you can use `var f = new Form(); f.Show();`. https://stackoverflow.com/questions/3965043/how-to-open-a-new-form-from-another-form – Selim Yildiz Jun 26 '20 at 08:04
  • I think it is not working. It just pop up a new form, without reloading the grid view – irham dollah Jun 26 '20 at 09:13
  • Put debugger the entrance of `Form1_Shown`. See if method is fired when you open the form. – Selim Yildiz Jun 26 '20 at 09:55