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;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
然后在button1的单击事件中添加如下代码:
private void button1_Click(object sender, EventArgs e)
{
returnValue = this.textBox1.Text;
this.Close();
}
- 1.
- 2.
- 3.
- 4.
- 5.
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;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
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();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
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;
}
........
........
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
更新父窗口中文本框中的值!
private void button1_Click(object sender, System.EventArgs e)
{
((Form1)_parentForm).txtContent.Text =this.txtValue .Text ;
}
- 1.
- 2.
- 3.
- 4.
C#实现WinForm传值的内容和相关的知识就向你介绍到这里,希望对你了解和学习C#实现WinForm传值的问题有所帮助。
【编辑推荐】