How to refresh datagridview when closing child form?

后端 未结 4 1099
南方客
南方客 2020-12-02 17:31

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 a

4条回答
  •  [愿得一人]
    2020-12-02 18:21

    There are many ways to do this, but the following is the simpliest and it will do what you want and get you started.

    • Create a public method on your main form.
    • Modified constructor of second form to take a main form.
    • Create an instance of the second form passing the main form object.
    • When closing second form, call the public method of the main form object.

    Form1

    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();
        }
    }
    

    Form2

    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();
        }
    }
    

提交回复
热议问题