//1 全域變數
//這個最簡單,只要把變數描述成static就可以了,在form2中直接引用form1的變數,代碼如下:
//在form1中定義一個static變數public static int i= 9 ;
//Form2中的鈕扣按鈕如下:
private void button1_Click(object sender, System.EventArgs e)
{textBox1.Text = Form1.i.ToString();}
//2 父視窗傳值給子視窗(Form1為主表單,Form2為子表單)
//代碼如下:
//Form1中的代碼:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnShow_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
//父表單傳值給子表單
Form1 form1 = new Form1();
form2.String1 = "成功傳值給Form2表單!";
form2.SetValue();
form2.ShowDialog();
}
//Form2中的代碼:
private string String;
public string String1
{
get { return String; }
set { String = value; }
}
public void SetValue()
{
this.lblText.Text = String1;
}
//3 子視窗傳值給父視窗(Form1為主表單,Form2為子表單)
//Form1中的代碼:
private string strValue;
public string StrValue
{
get { return strValue; }
set { strValue = value; }
}
private void btnShow_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
//子表單傳回值給父表單
form2.Owner = this;;//重要的一步,主要是使Form2的Owner指標指向Form1
form2.ShowDialog();
MessageBox.Show(StrValue);//顯示返回的值
}
//Form2中的代碼:
private void btnclose_Click(object sender, EventArgs e)
{
Form1 form1 = (Form1)this.Owner;//把Form2的父視窗指標賦給lForm1
form1.StrValue = "子表單成功傳回值給父表單!";//使用父視窗指標賦值
this.Close();
}
//第四:
//其實也是和第三中方法一樣的哦
winform1{};
winform2{public winform1 OWF =null; }