温馨提示×

winform怎么调用另外窗口的变量

小亿
121
2023-11-27 23:53:50
栏目: 智能运维

要调用另外窗口的变量,可以通过以下步骤实现:

  1. 在另外窗口的类中定义一个公共属性或者公共方法,用于获取或设置变量的值。
  2. 在调用另外窗口的地方,创建该窗口的实例,并通过实例访问该窗口的公共属性或方法来获取或设置变量的值。

下面是一个示例代码:

在另外窗口的类中定义一个公共属性或方法:

public class AnotherForm : Form
{
    public string Variable { get; set; }
}

在调用另外窗口的地方,创建该窗口的实例,并通过实例访问该窗口的公共属性或方法来获取或设置变量的值:

public partial class MainForm : Form
{
    private AnotherForm anotherForm;

    public MainForm()
    {
        InitializeComponent();
    }

    private void OpenAnotherFormButton_Click(object sender, EventArgs e)
    {
        anotherForm = new AnotherForm();
        anotherForm.Variable = "Hello World";
        anotherForm.Show();
    }

    private void GetVariableButton_Click(object sender, EventArgs e)
    {
        if (anotherForm != null)
        {
            string variableValue = anotherForm.Variable;
            MessageBox.Show(variableValue);
        }
    }
}

OpenAnotherFormButton_Click事件处理方法中,创建了AnotherForm的实例,并设置了其Variable属性的值。 在GetVariableButton_Click事件处理方法中,通过访问anotherForm实例的Variable属性来获取变量的值。

0