I've a dgv on my main form, there is a button that opens up another form to insert some data into the datasource bounded to the dgv. I want when child form closes the dgv auto refresh. I tried to add this in child form closing event, but it doesn't refresh:
private void frmNew_FormClosing(object sender, FormClosingEventArgs e) { frmMain frmm = new frmMain(); frmm.itemCategoryBindingSource.EndEdit(); frmm.itemsTableAdapter.Fill(myDatabaseDataSet.Items); frmm.dataGridView1.Refresh(); }
However, when I add this code in a button on the parent form, it actually does the trick:
this.itemCategoryBindingSource.EndEdit(); this.itemsTableAdapter.Fill(myDatabaseDataSet.Items); this.dataGridView1.Refresh();
There are many ways to do this, but the following is the simpliest and it will do what you want and get you started.
public partial class Form1 : Form { public Form1() { //'add a label and a buttom to form InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 oForm = new Form2(this); oForm.Show(); } public void PerformRefresh() { this.label1.Text = DateTime.Now.ToLongTimeString(); } }
public class Form2 : Form { Form1 _owner; public Form2(Form1 owner) { _owner = owner; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form2_FormClosing); } private void Form2_FormClosing(object sender, FormClosingEventArgs e) { _owner.PerformRefresh(); } }
We can also proceed this way:
We have form_1 and form_2
The method with our stuff is the method that will fill our form1 list, dataGridView, comboBox or whatever we want.
Form_1:
public fillComboBox()//Step 1. This is the method with your stuff in Form1 { foreach(var item in collection myInfo) {myComboBox.Items.Add(item)} }
Form_2:
Form1 instanceForm1;//Step 2 public Form2(Form1 theTransporter)//Step 3. This the Form2 contructor. { InitializeComponent(); instanceForm1 = theTransporter;//Step 4 } private void Form2_FormClosing(object sender, FormClosingEventArgs e) { instanceForm1.fillComboBox();//Step 5 we call the method to execute the task updating the form1 }
I hope it helps...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With