C# Winfrom窗體之間傳值
阿新 • • 發佈:2019-01-29
有任何錯誤之處請多指正。 多個WinForm窗體之間需要進行資料的傳遞,如何進行傳遞,如何更好的進行傳遞。 窗體之間傳值有五種方式(重點說委託) 1.使用建構函式進行例項化時進行傳值(無demo); 2.使用Tag進行傳值(無demo); 3.使用靜態資源進行傳值(無demo); 4.通過屬性進行傳值(無demo); 5.通過委託進行傳值 委託和lambda、Action、Func在之後的委託與事件、Lambda表示式等均會進行講解。 委託demo: 說明: Form1有一個Textbox和Button Form2有一個TextBox和三個Button
//Form1中Button的Click事件
private void btnSend_Click(object sender, EventArgs e)
{
//獲取TextBox的值
string inputValue = textBox1.Text.Trim();
//建立窗體
Form2 demoFrom = new Form2();
//委託進行窗體傳值
demoFrom.GetValue= delegate () {
return inputValue; };
//委託進行獲取值
demoFrom.SendValue = delegate(string a) {
this.textBox1.Text=a;
};
//委託進行獲取並傳遞值
demoFrom.GetAndSend = delegate(string a) {
string formValue = this.textBox1.Text;
this .textBox1.Text = a;
return formValue;
};
//展示
demoFrom.Show();
}
//Form2的三個委託
public Func<string> GetValue;
public Action<string> SendValue;
public Func<string, string> GetAndSend;
private void btnGet_Click(object sender, EventArgs e)
{
textBox1.Text = this.GetValue();
}
private void btnSend_Click(object sender, EventArgs e)
{
textBox1.Text += "。。。傳送,走你";
//不操作From進行From的TextBox的修改
this.SendValue(textBox1.Text);
}
private void btnGetAndSend_Click(object sender, EventArgs e)
{
this.textBox1.Text=this.GetAndSend("既獲取,又傳送");
}
Effect Picture:
![這裡寫圖片描述](https://img-blog.csdn.net/20170729215826672?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2FuZ194dWFu/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)