Windows Forms 應用程式常需在多個視窗(Form)間傳遞資料。本系列將介紹四種常見傳遞情境與實作方式。本文為第一篇,示範主視窗(Form1)向子視窗(Form2)傳遞字串的基礎模式。
FormDataPassing01,位置:E:\VS.NET Projects從工具箱拖曳至 Form1:
TextBox(textBox1、textBox2):輸入欲傳送資料Label(label1、label2):提示「歡迎詞:」、「提示訊息:」Button(button1,Text="發送"):雙擊產生 Click 事件處理函式取代預設 InitializeComponent 為手動建構介面程式碼(教學用途):
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
// button1
this.button1.Location = new System.Drawing.Point(103, 149);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 36);
this.button1.TabIndex = 0;
this.button1.Text = "發送";
this.button1.Click += new System.EventHandler(this.button1_Click);
// textBox1
this.textBox1.Location = new System.Drawing.Point(93, 56);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(122, 21);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "";
// textBox2
this.textBox2.Location = new System.Drawing.Point(93, 99);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(123, 21);
this.textBox2.TabIndex = 2;
this.textBox2.Text = "";
// label1
this.label1.Location = new System.Drawing.Point(29, 57);
this.label1.Name = "label1";
this.label1.TabIndex = 3;
this.label1.Text = "歡迎詞:";
// label2
this.label2.Location = new System.Drawing.Point(16, 100);
this.label2.Name = "label2";
this.label2.TabIndex = 4;
this.label2.Text = "提示訊息:";
// Form1
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(263, 223);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.textBox2, this.textBox1, this.button1, this.label2, this.label1 });
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
button1_Click 事件中將實作:
textBox1.Text、textBox2.TextForm2.Show() 或 ShowDialog() 顯示後續文章將陸續介紹:子視窗回傳資料給主視窗、多視窗雙向同步、應用程式層級共享資料等進階模式。請嘗試自行完成 Form2 設計與傳遞邏輯,驗證字串與數值傳遞效果。