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类型公共字段;

上述代码效果如下:

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值