分享

C#实现WinForm传值实例解析

 空城66 2014-11-29

    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();  

    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;  

    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. }  

    C#实现WinForm传值的内容和相关的知识就向你介绍到这里,希望对你了解和学习C#实现WinForm传值的问题有所帮助。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多