C ා use public fields to transfer form value instances

Keywords: Windows

Now there are 2 windows;

Start form2 from form1;

In form1, you need to initialize and set each control on form2 form to display the initial value;

At this time, the best way is to use the public fields of form2; the code looks clear;

form2 Code:

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; }
        }
    }
}

For the property value of the control to be transferred, define the public field and write its get and set methods;

form1 code;

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 = "Huang Feihong";
            f2.combo1 = "Guangzhou City";
            f2.num1 = 33;
            f2.rdchk1 = true;
            f2.txt2 = "Baozhilin Co., Ltd";
            f2.txt3 = "Shadowboxing";
            f2.ShowDialog();
        }
    }
}

After the public field is defined, the public field in form2 can be accessed in form1 and assigned;

Two text boxes of form2 define the public field of string type; value box define the public field of decimal type; assign value to the text property of combobox, and also define the public field of string type; to set whether to select from the radiobutton of form2 from form1, its checked property is bool type, and define the public field of bool type;

The effect of the above code is as follows:

 

Posted by purpleshadez on Mon, 18 Nov 2019 06:34:59 -0800