C#实现WinForm传值的方法

发布时间:2021-06-16 14:46:05 作者:chen
来源:亿速云 阅读:149

这篇文章主要讲解了“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;然后添加一个构造函数:

//定义一个变量,用来传值。  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传值的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. php页面传值的实现方法
  2. C#窗体传值代码方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:实现C#窗体间传值的方法

下一篇:使用C#怎么生成静态页面

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》