1询兴、構(gòu)造函數(shù)傳值,但這種方法是單向的(推薦)
private void button2_Click(object sender, EventArgs e)
{
Form3 fr3 = new Form3("要傳的值啊");
fr3.ShowDialog();
}
這里需要重載一個(gè)Form3的構(gòu)造函數(shù)起趾,然后將拿到的值顯示出來
public Form3(string canshu)
{
InitializeComponent();
label1.Text = canshu;
}
2诗舰、靜態(tài)變量傳值(不推薦)
以將靜態(tài)變量申明在你需要的地方,比如一個(gè)單獨(dú)類训裆,或者Form中眶根,比如我們?cè)谶@里申明在Form2中
public static string xvalue;
private void button2_Click(object sender, EventArgs e)
{
xvalue = "要傳的值啊xvalue";
Form3 fr3 = new Form3();
fr3.ShowDialog();
}
先給賦值,然后在Form3中取值
public Form3()
{
InitializeComponent();
label1.Text = Form2.xvalue;//Form2實(shí)際也是個(gè)class边琉,直接取靜態(tài)值即可属百,如果靜態(tài)變量xvalue定義在其他類中,即將Form2替換即可
}
3变姨、屬性傳值
首先在要打開的Form中創(chuàng)建一個(gè)共有屬性族扰,然后在調(diào)用窗口賦值即可。比如下面Form2啟動(dòng)Form3定欧,即給Form3的yvalue傳值
(1)在Form3中定義共有屬性
public string yvalue {
get
{
return label1.Text.ToString();
}
set
{
label1.Text = value;
}
}
(2)Form2中啟動(dòng)Form3渔呵,并傳值
private void button2_Click(object sender, EventArgs e)
{
Form3 fr3 = new Form3();
fr3.yvalue = "要傳的值啊";
fr3.ShowDialog();
}
4、通過Owner屬性傳值
(1)在調(diào)用者Form2中申明一個(gè)公有變量砍鸠,并賦值扩氢,設(shè)置需要啟動(dòng)的Form3的Owner
public string xvalue;
private void button2_Click(object sender, EventArgs e)
{
xvalue = "Form2要傳的值";
Form3 fr3 = new Form3();
fr3.Owner = this;
fr3.ShowDialog();
}
(2)啟動(dòng)窗體Form3中取值
private void Form3_Load(object sender, EventArgs e)
{
Form2 fr2 = (Form2)this.Owner;
label1.Text = fr2.xvalue;
}
這種方法實(shí)際是將Form2傳給了Form3,因此Form3可以取到Form2的所有公有變量和屬性爷辱。
5录豺、委托傳值(推薦)
委托傳值主要用在子窗體給父窗體傳值上,即上文的Form3給Form2傳值
(1)先在Form3中申明委托
public delegate void PutHandler(string text);
public PutHandler putTextHandler;//委托對(duì)象
private void button1_Click(object sender, EventArgs e)
{
if (putTextHandler != null)
{
putTextHandler(textBox1.Text.ToString());
}
}
(2)在Form2中綁定委托事件
public void getValue(string strV)
{
this.textBox1.Text = strV;
}
private void button1_Click(object sender, EventArgs e)
{
Form3 fr3 = new Form3();
fr3.putTextHandler = getValue;
fr3.ShowDialog();
}