說明:本文講解兩個窗體之間的傳值,主要用到兩個窗體,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一樣這里不做贅述