zoukankan      html  css  js  c++  java
  • C#实现WinForm传值实例解析

    C#实现WinForm传值的问题经常会做为公司面试的题目,那么作为学习C#以及WinForm传值,我们需要掌握哪些方法和思路呢?下面我们就向你介绍详细的思路和实现的具体步骤,希望对你有所帮助。

    C#实现WinForm传值的思路:

    从Form1传递到Form2: 2个窗体即两个类,两个窗体间的数据传送,可以采用构造函数来实现。

    从Form2返回到Form1,并传递数据:实例化Form2后,打f2用ShowDialog()方法,然后等待f2关闭时再回传数据到Form1。

    C#实现WinForm传值步骤及代码:

    1:新建两个窗口: Form1,Form2;

    2:打开Form2,添加一个textBox:textBox1;添加一个Button:button1;然后添加一个构造函数:

    1 //定义一个变量,用来传值。  
    2 public string returnValue ;  
    3  
    4 public Form2(string txtValue)  
    5 {  
    6   InitializeComponent();  
    7  
    8   this.textBox1.Text = txtValue;  
    9 }  

    然后在button1的单击事件中添加如下代码:

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

    3:Form1中添加一个textBox:textBox1;添加一个Button:button1;然后在button1的单击事件中添加如下代码:

    1 private void button1_Click(object sender, EventArgs e)  
    2 {  
    3   string txtValue = this.textBox1.Text;  
    4   Form2 f2 = new Form2(txtValue);  
    5   f2.ShowDialog();  
    6   this.textBox1.Text = f2.returnValue;  
    7 } 

    Form1 中 (父窗口:)

     1 public class Form1 : System.Windows.Forms.Form  
     2 {  
     3  private System.Windows.Forms.Button btnOpen;  
     4  public System.Windows.Forms.TextBox txtContent;   
     5 //注意是public  
     6  
     7   ........  
     8  
     9   ........  
    10  
    11  [STAThread]  
    12 static void Main()  
    13 {  
    14 Application.Run(new Form1());  
    15 }  
    16  
    17  private void btnOpen_Click(object sender, System.EventArgs e)  
    18  {  
    19   Form2 frm=new Form2(this);  
    20   frm.ShowDialog();  
    21  }  
    22  
    23 }  

    Form2中(子窗口)

     1 public class Form2 : System.Windows.Forms.Form  
     2 {  
     3  private System.Windows.Forms.Button button1;  
     4  private System.Windows.Forms.TextBox txtValue;  
     5  
     6  private Form _parentForm=null;  
     7  
     8   public Form2()  
     9   {  
    10   InitializeComponent();   
    11   }  
    12  
    13  public Form2(Form parentForm)  
    14  {  
    15 InitializeComponent();  
    16 this._parentForm =parentForm;  
    17  }  
    18  
    19  ........  
    20  
    21 ........  

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

    1 private void button1_Click(object sender, System.EventArgs e)  
    2 {  
    3  ((Form1)_parentForm).txtContent.Text =this.txtValue .Text ;  
    4 }  
  • 相关阅读:
    第32周二
    第32周一
    第31周日
    第31周六
    第31周五
    第31周四
    第31周三
    C++中this指针的使用方法.
    ArcPad 10 的安装部署
    UEditor用法
  • 原文地址:https://www.cnblogs.com/SJP666/p/4788943.html
Copyright © 2011-2022 走看看