在 VS2008 (C#) 中,常見需求是從主表單 Form1 開啟子表單 Form2 並傳遞資料。三種主流做法:
// Form2
public Form2(string userName, int age) {
InitializeComponent();
lblUser.Text = userName;
lblAge.Text = age.ToString();
}
// Form1 呼叫
new Form2(txtUser.Text, int.Parse(txtAge.Text)).Show();
// Form2
public string UserName { get; set; }
public int Age { get; set; }
// Form1
var f2 = new Form2();
f2.UserName = txtUser.Text;
f2.Age = int.Parse(txtAge.Text);
f2.Show();
// Form2 定義事件
public event Action DataSubmitted;
private void btnOk_Click(...) => DataSubmitted?.Invoke(txtUser.Text, int.Parse(txtAge.Text));
// Form1 訂閱
var f2 = new Form2();
f2.DataSubmitted += (u, a) => { /* 更新 Form1 UI */ };
f2.Show();
建議優先用建構子或屬性傳單向資料;需雙向互動才引入事件。切記:VS2008 只是 IDE,語言特性取決於 C# 版本,專案目標框架請設為 .NET Framework 3.5 以上。