在C#中窗体间怎么传值
简单的事例一下:
form1中需要4个label,一个textbox,两个RadioButton,一个comboBox,一个dateTimePicker,一个Button这些控件,代码如下:
using System.Windows.Forms;
namespace formchuanzhi1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 f2;
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请写上名字");
return;
}
if (radioButton1.Checked ==false && radioButton2.Checked ==false )
{
MessageBox.Show("请选择性别");
return;
}
if(comboBox1 .SelectedIndex ==-1)
{
MessageBox .Show ("请选择职业");
return ;
}
if(DateTime .Parse (dateTimePicker1 .Value .ToLongDateString ())>=DateTime .Parse (DateTime .Now .ToLongDateString ()))
{
MessageBox .Show ("不可能");
return ;
}
f2 = new Form2(textBox1 .Text ,radioButton1.Checked ?radioButton1.Text :radioButton2 .Text , comboBox1.SelectedItem .ToString (),dateTimePicker1 .Value.ToLongDateString () );
f2.Show();
}
}
}
在form2中需要8个label控件,代码如下:
using System.Windows.Forms;
namespace formchuanzhi1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Form2(string name,string sex,string professor,string birthday)
{
InitializeComponent();
this.label5.Text = name;
this.label6.Text = sex;
this.label7.Text = professor;
this.label8.Text = birthday;
}
}
}
class MyForm:Form{
....
private string something;
public string Something{get{return something;}set{something=value;}}
}
通过类似这种属性来传值:form1.Something=xxx
2、另一种是建立一个中间件来存储数据,比如建立一个Record类:
class Record{
public static string Something;
}
二个窗体互传值时通过Record.Something来设置和调用值:
比如在form1中调用 Record.Something="something"来设置要传的值,在form2中调用
xxx=Record.Something 来接收传来的值
Form2中接收 : Form1 lvFrm = new Form1();
string lvFrm2=""; //Form2中接收的变量
lvFrm2 = lvFrm.lvStr;