How can I pass values from one form to another?

前端 未结 10 2600
野的像风
野的像风 2020-12-02 00:43

Consider the situation where I have two windows forms, say F1 and F2. After using F1, I have now called F2.ShowDialog().

10条回答
  •  悲&欢浪女
    2020-12-02 01:18

    Use a defined Type for your information (class, struct...) and declare a variable of that in Form1

    struct myData
    {
        String str1;
        String str2;
    }
    
    Public Class Form1
    {
      Public myData dat;
    }
    

    (Note: the type shouldnt really be public, this is just for the sake of this example) Thus the data sits within Form1. Modify the constructor of Form2 to accept a parameter of type Form1.

    public Form2(Form1 frm1)
    {
        mFrm1 = frm1;
        InitializeComponent();
    }
    

    Now, when you call form2, send in the very instance of Form1 that's making the call:

    Form2 frm2 = new Form2(this);
    frm2.ShowDialog();
    

    Now, when execution has reached Form2, you can access the MyData within Form1:
    mFrm1.dat;

    In this way, both instances of Form1 and Form2 will be referencing the data that's in one place. Making changes/updates will be available for both instances of the forms.

提交回复
热议问题