How to pass string value from one form to another form's load event in C #

后端 未结 5 480
我寻月下人不归
我寻月下人不归 2020-12-03 15:12

I need to pass a string value from Form1:

public void button1_Click(object sender, EventArgs e)
{
    string DepartmentName = \"IT\";
    Form2          


        
相关标签:
5条回答
  • 2020-12-03 15:43

    You don't do it that way. Instead you can pass your string value on the constructor:

    public class Form2 
    {
        public Form2(string myParameter) : this()
        {
            //do whatever you need to do with myParameter
        }
    }
    

    the other answerers have also told you how to do it with a public property.

    0 讨论(0)
  • 2020-12-03 15:48

    There is an easier way to pass the string from Form2 to Form1. Create a relationship between the forms and in Form2, create a variable of Form1, invoke the variable in Form1 and assign the value to it ....

    public partial class Form_2 : Form
        {
            public readonly Form1 _form1;
            public Form_2(Form1 form1)
            {
                _form1 = form1;
                InitializeComponent();
            }         
            private void Form2(object sender, EventArgs e)
            {     
                _form1.Remark = txtbx_remark.Text;                  
            }// Remark is a string in Form1 .... 
    
    0 讨论(0)
  • 2020-12-03 15:52

    PRO TIP

    In the future, think about it in a more generic way: a Form is just a class, and the Load event is just a method.

    If you were trying to pass a value between 2 objects that weren't Forms, you would have a public property in one class that other objects could access. This is at the heart of rsbarro's answer, and what I like to call "Forms are classes too" :)

    0 讨论(0)
  • 2020-12-03 15:56

    Just create a property on the Form2 class and set it before you show Form2.

    public class Form2
    {
       ...
       public string MyProperty { get; set; }
    
       private void Form2_Load(object sender, EventArgs e)
       {
           MessageBox.Show(this.MyProperty);
       }
    }
    

    From Form1:

    public void button1_Click(object sender, EventArgs e)
    {
        string departmentName = "IT";
        Form2 frm2 = new Form2();
        frm2.MyProperty = departmentName;
        frm2.Show();
        this.Hide();
    }
    
    0 讨论(0)
  • 2020-12-03 16:00

    Remember that forms are just classes like any other

    public class Form2 : form
    {
       public string ShowMe {get;set;}
       private void Form2_Load(object sender, EventArgs e)
       {
           MessageBox.Show(ShowMe);
    
       }
    
    }
    

    From Form 1

    public void button1_Click(object sender, EventArgs e)
    {
        string DepartmentName = "IT";
        Form2 frm2 = new Form2();
        frm2.ShowMe = DepartmentName ;
        Frm2.Show();
        this.Hide();
    
    
    }
    
    0 讨论(0)
提交回复
热议问题