How do I pass data from child of child form to parent form in C#?

后端 未结 3 1969
暖寄归人
暖寄归人 2021-01-21 02:42

I am new to c#. I have the following in my project in windows forms:

Form1 with button and DataGridView.

Form2 with button.

Form3 with button and 3 text

3条回答
  •  没有蜡笔的小新
    2021-01-21 03:03

    You cannot expect to get complete code that's ready to be pasted. I quickly wrote this in notepad to give you idea about how events work best in such cases. I assumed Form1 directly opens Form3. Solution below shows how to use events.

    You home work is to make it work by adding another form Form2 in between. You can do so by propagating same event via Form2 which sits in middle.

    Form3.cs

    public partial class Form3 : Form
    {
        public event EventHandler RecordAdded
    
        public Form3()
        {
            InitializeComponent();
        }
    
        private void buttonAddRow _Click(object sender, EventArgs e)
        {
            OnRecordAdded();
        }
    
        private void OnRecordAdded() {
            var handler = RecordAdded;
            if(RecordAdded != null) {
                RecordAdded.Invoke(this, new AddRecordEventArgs(txtQty.Text, txtDesc.Text, txtPrice.Text))
            }
        }
    }
    

    AddRecordEventArgs.cs

    public class AddRecordEventArgs : EventArgs
    {
        public AddRecordEventArgs(string qty, string desc, string price) {
            Quantity = qty;
            Description = desc;
            Price = price;
        }
    
        public int Quantity { get; private set; }
        public string Description { get; private set; }
        public decimal Price { get; private set; }
    }
    

    Form1.cs

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void buttonOpenForm3_Click(object sender, EventArgs e)
        {
            Form3 frm3 = new Form3();
            frm3.RecordAdded += Form3_RecordAdded;
            frm3.Show();
        }
    
        private void Form3_RecordAdded(object sender, AddRecordEventArgs e) {
            // Access e.Quantity, e.Description and e.Price
            // and add new row in grid using these values.
        }
    }
    

提交回复
热议问题