溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#實(shí)現(xiàn)WinForm傳值的方法

發(fā)布時(shí)間:2021-06-16 14:46:05 來(lái)源:億速云 閱讀:156 作者:chen 欄目:編程語(yǔ)言

這篇文章主要講解了“C#實(shí)現(xiàn)WinForm傳值的方法”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“C#實(shí)現(xiàn)WinForm傳值的方法”吧!

C#實(shí)現(xiàn)WinForm傳值的思路:

從Form1傳遞到Form2: 2個(gè)窗體即兩個(gè)類(lèi),兩個(gè)窗體間的數(shù)據(jù)傳送,可以采用構(gòu)造函數(shù)來(lái)實(shí)現(xiàn)。

從Form2返回到Form1,并傳遞數(shù)據(jù):實(shí)例化Form2后,打f2用ShowDialog()方法,然后等待f2關(guān)閉時(shí)再回傳數(shù)據(jù)到Form1。

C#實(shí)現(xiàn)WinForm傳值步驟及代碼:

1:新建兩個(gè)窗口: Form1,Form2;

2:打開(kāi)Form2,添加一個(gè)textBox:textBox1;添加一個(gè)Button:button1;然后添加一個(gè)構(gòu)造函數(shù):

//定義一個(gè)變量,用來(lái)傳值。  public string returnValue ;   public Form2(string txtValue)  {    InitializeComponent();     this.textBox1.Text = txtValue;  }

然后在button1的單擊事件中添加如下代碼:

private void button1_Click(object sender, EventArgs e)  {    returnValue = this.textBox1.Text;    this.Close();  }

3:Form1中添加一個(gè)textBox:textBox1;添加一個(gè)Button:button1;然后在button1的單擊事件中添加如下代碼:

private void button1_Click(object sender, EventArgs e)  {    string txtValue = this.textBox1.Text;    Form2 f2 = new Form2(txtValue);    f2.ShowDialog();    this.textBox1.Text = f2.returnValue;  }

Form1 中 (父窗口:)

public class Form1 : System.Windows.Forms.Form  {   private System.Windows.Forms.Button btnOpen;   public System.Windows.Forms.TextBox txtContent;   //注意是public     ........     ........    [STAThread]  static void Main()  {  Application.Run(new Form1());  }    private void btnOpen_Click(object sender, System.EventArgs e)   {    Form2 frm=new Form2(this);    frm.ShowDialog();   }   }

Form2中(子窗口)

public class Form2 : System.Windows.Forms.Form  {   private System.Windows.Forms.Button button1;   private System.Windows.Forms.TextBox txtValue;    private Form _parentForm=null;     public Form2()    {    InitializeComponent();     }    public Form2(Form parentForm)   {  InitializeComponent();  this._parentForm =parentForm;   }    ........   ........

更新父窗口中文本框中的值!

private void button1_Click(object sender, System.EventArgs e)  {   ((Form1)_parentForm).txtContent.Text =this.txtValue .Text ;  }

感謝各位的閱讀,以上就是“C#實(shí)現(xiàn)WinForm傳值的方法”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)C#實(shí)現(xiàn)WinForm傳值的方法這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI