-12

How do i pass name value from Form1 to Form2?

Form1

public partial class Form1 : Form
{
    public string name = "xxx";
}

Form2

public partial class Form2 : Form
{
    private void Form2_Load(object sender, EventArgs e)
    {
        lblname.Text = name;
    }
}

Solution:

Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string name = "xxx";
        Form2 frm2 = new Form2(name);
        frm2.Show();
    }
}

Form2

public partial class Form2 : Form
{
    public Form2(string name)
    {
        InitializeComponent();
        label1.Text = name;
    }
}
Community
  • 1
  • 1
Cristian Muscalu
  • 9,007
  • 12
  • 44
  • 76

1 Answers1

0

One easy but not recommended solution would be to make the field static:

public partial class Form1 : Form
{
    public static string name = "xxx";
}

Then you can simply read it from the other form:

public partial class Form2 : Form
{
    lblName.Text = Form1.name;
}
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • 1
    Using static variables is a recipe for disaster. I've worked on forms apps written this way, and, unless you want to spend your career chasing down impossible-to-find bugs, static variables should be reserved for global, mostly-immutable data. – DVK Jul 28 '16 at 15:39
  • @DVK I totally agree with you. In fact, I did clarify that this is not recommended at all. – Matias Cicero Jul 28 '16 at 16:24