简体   繁体   中英

How To access winforms parent Form controls from a child Form

In Form1 I have one DataGridView and multiple textboxes. When I click A button in Form2 I need to save the data from DataGridView and multiple textboxes to Database. How to Implement in C sharp Windows Application

Form1 Button Click event. I opened Form2

 public sealed partial class form1 : Form
 {
   private static form1 instance = null;
    public static form1 Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new form1();
            }
            return instance;
        }
    }

  private void button1_Click(object sender, EventArgs e)
    {
        textbox2.Text=100;
        form2 CO = new form2();
        CO.Show();
    }
}

I want to attach textboxes data and Datagridview content to object SO and Call InsertSale function .textboxes and datagridview are in form1

This is Button Click Event in Form 2

  private void button1_Click(object sender, EventArgs e)
  {
      clsSale SO = new clsSale();
      SO.Totamount = Convert.ToDecimal(form1.Instance.textBox2.Text);

      SO.InserSale(SO);
   }

If Form2 wants to access the Form1 properties.

Pass ParentForm instance to the ChildForm constructor. Add a public method in the parent form to update its properties from child form.

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void SetTextBoxValue(string val)
    {
        this.textBox1.Text = val;
    }

    private void CreateForm2()
    {
         var form2 = new Form2(this);
         form2.Show();
    }
}

public partial class Form2: Form
{
    private Form1 form1;

    public Form2(Form1 frm1)
    {
        InitializeComponent();

        form1= frm1;
        form1.SetTextBoxValue("Value from Form2");
    }   
}

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