WinForms: Pass Data Between Forms

There are several ways to pass values between WinForms windows:

  1. Constructor: Pass parameters to the window’s constructor when creating an instance of the form. For example:
Form2 form2 = new Form2(valueToPass);
form2.Show();
  1. Properties: values can be passed between forms by defining common properties. For example:
public partial class Form2 : Form
{
    public string ValueToReceive { get; set; }

    public Form2()
    {
        InitializeComponent();
    }
}

Setting the value of a property in another window and accessing it:

Form2 form2 = new Form2();
form2.ValueToReceive = "Value to pass";
form2.Show();
  1. Static variables: It is possible to define static variables in a static class to store passed values. For example:
public static class Globals
{
    public static string ValueToPass { get; set; }
}

// 在一个窗体中设置值
Globals.ValueToPass = "Value to pass";

// 在另一个窗体中获取值
string value = Globals.ValueToPass;

These are some common methods for passing values between WinForms windows, you can choose the appropriate way based on specific requirements.

bannerAds