C# 使用公共字段进行窗体传值实例
生活随笔
收集整理的這篇文章主要介紹了
C# 使用公共字段进行窗体传值实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
現假設有2個窗體;
從form1啟動form2;
需要在form1中,初始化設置form2窗體上的各個控件;使其顯示初始值;
此時最好的方法是用form2的公共字段;代碼看上去比較清晰;
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 chzhdemo1 {public partial class Form2 : Form{public Form2(){InitializeComponent();}private void Form2_Load(object sender, EventArgs e){}public string txt1{set { textBox1.Text = value; }get { return textBox1.Text; }}public string combo1{set { comboBox1.Text = value; }get { return comboBox1.Text; }}public decimal num1{set { numericUpDown1.Value = value; }get { return numericUpDown1.Value; }}public bool rdchk1{set { radioButton1.Checked = value; }get { return radioButton1.Checked; }}public string txt2{set { textBox2.Text = value; }get { return textBox2.Text; }}public string txt3{set { textBox3.Text = value; }get { return textBox3.Text; }}} }對要傳值的控件,的屬性值,定義公共字段,寫好它的get、set方法;
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 chzhdemo1 {public partial class Form1 : Form{Form2 f2;public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){f2 = new Form2();f2.txt1 = "黃飛鴻";f2.combo1 = "廣州市";f2.num1 = 33;f2.rdchk1 = true;f2.txt2 = "寶芝林有限公司";f2.txt3 = "無影拳";f2.ShowDialog();}} }定義了公共字段以后在form1可以訪問form2中的公共字段;進行賦值;
form2的2個文本框,定義string類型的公共字段;數值框,定義decimal類型的公共字段;為combobox的text屬性賦值,也定義string類型的公共字段;要從form1設置form2的radiobutton選中與否,其checked屬性是bool類型,定義bool類型公共字段;
上述代碼效果如下:
?
總結
以上是生活随笔為你收集整理的C# 使用公共字段进行窗体传值实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用超图桌面版制作点图层并发布为地图服务
- 下一篇: 正则表达式基本内容