简体   繁体   中英

How to reload the data grid view during runtime c#

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM