2012-01-11 77 views
0

我有一個窗體,我創建的應該載入登錄信息/設置是從主窗體分離。我想知道如何將這些信息從一種形式傳遞給另一種形式。C#通過窗體關閉事件傳遞對象

我想你需要使用表單封閉事件(我將在表單關閉時傳遞信息)。但我不確定如何去做。

+0

您是否從用戶那裏獲得登錄/設置信息?如果沒有,你有沒有考慮從配置文件加載它? – Abbas 2012-01-11 03:58:25

回答

1

不,您可以使用屬性或快速解決方案。在獲取信息的表單中,返回屬性的數據:

public readonly int Age { 
    get { 
     return int.Parse(this.txtAge.Text); 
    } 
} 

例如。然後您就可以訪問它像任何其他財產形式已經關閉後:

SomeForm someForm = new SomeForm(); 
someForm.ShowDialog(); 
int userAge = someForm.Age; 
0

一般有兩種方法來這樣做。最直接的方法是向加載完成登錄信息時引發的幫助程序表單添加新事件。然後主窗體可以聽這個事件。一旦收到,它可以關閉助手的形式。

class LoginInformationEventArgs : EventArgs { 
    ... 
} 

class HelperForm : Form { 
    ... 
    public event EventHandler<LoginInformationEventArgs> LoginInformationLoaded; 
    ... 
} 

class MainForm : Form { 
    LoginInformationEventArgs _loginInfo; 

    public void ShowHelper() { 
    var helper = new HelperForm(); 
    helper.LoginInformationLoaded += delegate (sender, e) { 
     _loginInfo = e; 
     helper.Close(); 
    }; 
    helper.Show(); 
    } 
} 

第二種方法是在助手窗體上使用屬性。表單負責在關閉之前設置它們,然後主對話框可以在完成後直接從輔助表單中讀取它們。

class LoginInformation { 
    ... 
} 

class HelperForm : Form { 
    public LoginInformation { get; set; } 
    private void OnCompleted() { 
    LoginInformation = ... 
    this.Close(); 
    } 
} 

class MainForm : Form { 
    public void ShowHelper() { 
    var helper = new HelperForm(); 
    helper.ShowDialog(this); 
    Process(helper.LoginInformation); 
    } 
}