简体   繁体   中英

Fill created form components from another form in C#

i create a new form using the code below.

private void CNPictureBox2_DoubleClick(object sender, EventArgs e)
{
    RefImgForm RefImgForm = new RefImgForm();
    RefImgForm.MainFrm = this;
    RefImgForm.Show();
}

I want to send data from the form that i create second form. The problem is that i cannot send data to the new form when creating it. I want to send data when i take some data from user and then send this data by button click event. How can i do that?

Define a new method in second form

public void ReceiveData(....)
{
...
}

and call this from first form on button click

private RefImgForm frm2 = null;
private void CNPictureBox2_DoubleClick(object sender, EventArgs e)
{
    frm2 = new RefImgForm();
    frm2.MainFrm = this;
    frm2.Show();
}
private void Button_Click(...)
{
    if (frm2 != null)
        frm2.ReceiveData(...);
}

Create a delegate in the parent form like this:

      delegate void SendData(object data);
      SendData sendDataobj;

make a method in the child form like ProcessData and use the following code:

private void CNPictureBox2_DoubleClick(object sender, EventArgs e)
{
    RefImgForm RefImgForm = new RefImgForm();
    RefImgForm.MainFrm = this;
    sendDataobj = new SendData(RefImgForm.ProcessData)
    RefImgForm.Show();
}

for calling the delegate you can use:

    sendDataobj(data);
    sendDataobj.Invoke(data);

both are synchronous calls.

if you want to call it asynchronously you can use:

sendDataobj.BeginInvoke

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