Update DataGridView after Child Form Closed

后端 未结 2 1968
抹茶落季
抹茶落季 2021-01-16 04:11

I know lot of similar questions are out there. But, I\'m really new to C# so, cannot figure out how to solve this.

I have a DataGridView on main form a

相关标签:
2条回答
  • 2021-01-16 04:25

    This is just a sample, how you call the public method in main form from child form:

    public class Products : Form
    {
        public void UpdateProductList()
        {
            // do something here
        }
    
        private void buttonOpenChildFormClick(object sender, EventArgs e)
        {
            using (var addProduct = new Add_product(this)) //send this reference of MainForm to ChildForm
            {
                addProduct.ShowDialog();
            }
        }
    }
    
    public class Add_product : Form
    {
        private readonly Products _products;
    
        public Add_product(Products products) //send reference of MainForm to ChildForm
        {
            _products = products;
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            _products.UpdateProductList();
        }
    }
    
    0 讨论(0)
  • 2021-01-16 04:33

    When you show the child form using ShowDialog yo don't need to call LoadData from child form, instead you can check the result of ShowDialog and if it was DialogResult.OK, call the method.

    Also in your child form, in your save button after saving data, set this.DialogResult = DialogResult.OK.

    Show Child Form

    using (var f = new ChildForm())
    {
        if(f.ShowDialog()== System.Windows.Forms.DialogResult.OK)
            this.LoadData(); /*Load data in list form*/
    }
    

    Save Button in Child Form

    this.SaveData(); /*Save Data in child form */
    this.DialogResult = System.Windows.Forms.DialogResult.OK;
    

    Note

    • When ShowDialog is called, the code following it is not executed until after the dialog is closed.
    • If you show a form using ShowDialog, setting DialogResult property of Form closes the form.
    • You can set DialogResult to OK in your save button and set it to Cancel in your cancel button.
    • Currently your problem is in code of your save button, you have created a new instance of your list form and called its UpdateProductsList method. It doesn't have any impact on the open instance of your list form which you can see. It's a different isntace.
    0 讨论(0)
提交回复
热议问题