溫馨提示×

winform怎么調用另外窗口的變量

小億
173
2023-11-27 23:53:50
欄目: 智能運維

要調用另外窗口的變量,可以通過以下步驟實現(xiàn):

  1. 在另外窗口的類中定義一個公共屬性或者公共方法,用于獲取或設置變量的值。
  2. 在調用另外窗口的地方,創(chuàng)建該窗口的實例,并通過實例訪問該窗口的公共屬性或方法來獲取或設置變量的值。

下面是一個示例代碼:

在另外窗口的類中定義一個公共屬性或方法:

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

在調用另外窗口的地方,創(chuàng)建該窗口的實例,并通過實例訪問該窗口的公共屬性或方法來獲取或設置變量的值:

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事件處理方法中,創(chuàng)建了AnotherForm的實例,并設置了其Variable屬性的值。 在GetVariableButton_Click事件處理方法中,通過訪問anotherForm實例的Variable屬性來獲取變量的值。

0