The C value transfer method realizes the communication instance between different program forms

  • 2020-05-24 06:04:11
  • OfStack

When the AcceptChange button of Form2 is pressed, the value of the corresponding column in ListBox of Form1 needs to be modified. Therefore, the ListBox control in Form1 can be considered to be passed into Form2 at the same time when the parameter is also passed into Form2. All modification work is completed in Form2.


publicpartial class Form2 : Form     
    {     
        private string text;     
        private ListBox lb;     
        private int index;     

       // Constructor reception 3 Select the line text, ListBox Control to select the row index      
        public Form2(string text,ListBox lb,int index)     
        {     
            this.text = text;     
            this.lb = lb;     
            this.index = index;     
            InitializeComponent();     
            this.textBox1.Text = text;     
        }     

        private void btnChange_Click(object sender, EventArgs e)     
        {                
            string text = this.textBox1.Text;     
            this.lb.Items.RemoveAt(index);     
            this.lb.Items.Insert(index, text);     
            this.Close();     
        }     
    }

In Form1, new form 2 says:


public partial class Form1 :Form     
    {     
        int index = 0;     
        string text = null;     
        public Form1()     
        {     
            InitializeComponent();     
        }     

        private void listBox1_SelectedIndexChanged(object sender, EventArgse)     
        {                 
            if (this.listBox1.SelectedItem != null)     
            {     
                text = this.listBox1.SelectedItem.ToString();     
                index = this.listBox1.SelectedIndex;     

               // structure Form2 Simultaneous parameter passing      
                Form2 form2 = new Form2(text, listBox1, index);     
                form2.ShowDialog();     
            }     
       }

OK, the advantage of this is that it is intuitive to upload whatever you need, and the disadvantage is obvious. If you need to modify 100 controls in form 1, how can you pass 100 parameters in the construction? Moreover, if other forms still need to play Form2, then Form2 is invalid and can only be used by form 1, unless overloaded constructors are written, which is not conducive to code reuse


Related articles: