WinForm視窗之間傳遞值

來源:互聯網
上載者:User
//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; }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.