C#实现WinForm传值的方法

这篇文章主要讲解了“C#实现WinForm传值的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C#实现WinForm传值的方法”吧!

创新互联公司是专业的静宁网站建设公司,静宁接单;提供成都网站设计、网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行静宁网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

C#实现WinForm传值的思路:

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

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

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

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

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

//定义一个变量,用来传值。  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中添加一个textBox:textBox1;添加一个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#实现WinForm传值的方法”的内容了,经过本文的学习后,相信大家对C#实现WinForm传值的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!

分享题目:C#实现WinForm传值的方法
当前网址:https://www.cdcxhl.com/article34/jghdpe.html

成都网站建设公司_创新互联,为您提供定制网站面包屑导航软件开发网站建设企业网站制作响应式网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

微信小程序开发