C#實(shí)現(xiàn)WinForm傳值實(shí)例解析
C#實(shí)現(xiàn)WinForm傳值的問題經(jīng)常會(huì)做為公司面試的題目,那么作為學(xué)習(xí)C#以及WinForm傳值,我們需要掌握哪些方法和思路呢?下面我們就向你介紹詳細(xì)的思路和實(shí)現(xiàn)的具體步驟,希望對你有所幫助。
C#實(shí)現(xiàn)WinForm傳值的思路:
從Form1傳遞到Form2: 2個(gè)窗體即兩個(gè)類,兩個(gè)窗體間的數(shù)據(jù)傳送,可以采用構(gòu)造函數(shù)來實(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:打開Form2,添加一個(gè)textBox:textBox1;添加一個(gè)Button:button1;然后添加一個(gè)構(gòu)造函數(shù):
- //定義一個(gè)變量,用來傳值。
- 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)容和相關(guān)的知識就向你介紹到這里,希望對你了解和學(xué)習(xí)C#實(shí)現(xiàn)WinForm傳值的問題有所幫助。
【編輯推薦】