C#實現兩個窗體之間數值傳送的方法
更新時間:2015年11月28日 14:40:31 作者:期待秋天的葉
這篇文章主要介紹了C#實現兩個窗體之間數值傳送的方法,涉及C#中WinForm窗體數值傳遞的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#實現兩個窗體之間數值傳送的方法。分享給大家供大家參考,具體如下:
以下是本人常用的方法,其實方法很多,但我覺得這兩種我比較好理解,要是哪位朋友有比較簡單的易懂的其他方法,希望不吝賜教。
方法一:
比如要在FORM2里得到FORM1里的值,先在FORM1里定義一個公有的字符串
復制代碼 代碼如下:
public string zhi="xxxxxx";
然后FORM2里用FORM1去實例化一個對象
復制代碼 代碼如下:
FORM1 f=new FORM1();
最后用 f.zhi來取得FORM1里的值。(f.Show()也是一個道理,即對象名.方法名)
方法二:
比如要在FORM1里得到FORM2里的值,利用GET,SET方法。
在FORM2里放一個TEXTBOX,寫一個公有屬性
public string transsformValue { get { return this.textBox1.Text; } set { this.textBox1.Text=value; } }
在FORM1里這么寫(在里面也加一個TEXTBOX):.
FORM2 f=new FORM2(); f.transsformValue="aaaa"; textBox1=f.transsformValue; f.Show();
這樣運行后是將FORM2的文本框的值設為“aaaa”,并且顯示在FORM1里的文本框里
實例演示
FORM1里這么寫:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication17 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { InputBox f = new InputBox(); f.Title = "請輸入對話框"; f.TipText = "請輸入年齡"; if (f.ShowDialog() == DialogResult.OK) this.label1.Text = f.Message; } } } //InputBox的FORMl里這么寫 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication17 { public partial class InputBox : Form { public InputBox() { InitializeComponent(); } public string Title { set { this.Text = value; } } public string Message { get { return this.Input.Text; } } public string TipText { set { this.Tip.Text = value; } } private void InputBox_Load(object sender, EventArgs e) { this.AcceptButton = this.btnOK; this.CancelButton = this.btnCancel; this.btnOK.DialogResult = DialogResult.OK; this.btnCancel.DialogResult = DialogResult.Cancel; } } }
運行效果截圖如下:
希望本文所述對大家C#程序設計有所幫助。