首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# Windows Forms 視窗間資料傳遞四大模式實作(一):主視窗向子視窗傳字串

     編輯:關於C#

Windows Forms 應用程式常需在多個視窗(Form)間傳遞資料。本系列將介紹四種常見傳遞情境與實作方式。本文為第一篇,示範主視窗(Form1)向子視窗(Form2)傳遞字串的基礎模式。

開發環境

  • Windows 2000 Server
  • Visual Studio .NET (正式版)
  • .NET Framework SDK v1.0.3705

專案建立步驟

  1. 啟動 VS.NET → 檔案 → 新增專案
  2. 專案類型:Visual C# 專案,範本:Windows 應用程式
  3. 名稱:FormDataPassing01,位置:E:\VS.NET Projects

Form1 介面設計

從工具箱拖曳至 Form1:

  • 兩個 TextBox(textBox1、textBox2):輸入欲傳送資料
  • 兩個 Label(label1、label2):提示「歡迎詞:」、「提示訊息:」
  • 一個 Button(button1,Text="發送"):雙擊產生 Click 事件處理函式

Form1 程式碼實作

取代預設 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 事件中將實作:

  1. 建立 Form2 實例
  2. 透過 Form2 的公開屬性或建構函式傳入 textBox1.Text、textBox2.Text
  3. 呼叫 Form2.Show() 或 ShowDialog() 顯示

後續文章將陸續介紹:子視窗回傳資料給主視窗、多視窗雙向同步、應用程式層級共享資料等進階模式。請嘗試自行完成 Form2 設計與傳遞邏輯,驗證字串與數值傳遞效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved