说明:本文讲解两个窗体之间的传值,主要用到两个窗体,form1,form2
1、在form1窗体单击按钮,打开窗体form2,然后把form2中文本框的值传递给form1
form1中的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FormToform
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//获取值
private void button1_Click(object sender, EventArgs e)
{
Form2 fr = new Form2();
DialogResult rsult = fr.ShowDialog();
if(rsult==DialogResult.OK)
{
//获取窗体2传回来的值
listBox1.Items.Add(fr.UKind);
listBox1.Items.Add(fr.UName);
}
}
}
}
窗体form2的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FormToform
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
//给窗体定义两个属性
public string UKind {
get { return textBox1.Text; }
set { textBox1.Text= value; }
}
public string UName
{
get { return textBox2.Text; }
set { textBox2.Text = value; }
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
}
}
2、在form1窗体单击按钮,打开窗体form2,然后给form2中文本框赋值
form1中按钮的代码如下:
private void button2_Click(object sender, EventArgs e)
{
Form2 fr = new Form2();
fr.UName = "姓名";
fr.UKind = "类别";
DialogResult rsult = fr.ShowDialog();
}
form2与标题1一样这里不做赘述