-13

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;
    }
}
10
  • 11
    Asked thousand times, google your title which you should have done before you've asked this. Commented Jul 28, 2016 at 14:37
  • Should i have mentioned i searched 100 times? Commented Jul 28, 2016 at 14:40
  • 3
    Then you need to work on your googling skills. I feel like I see this question asked (and closed as a dupe) every other day. Commented Jul 28, 2016 at 14:41
  • 2
    @Cris google.com/search?q=Winforms+C%23+pass+variable+between+forms Commented Jul 28, 2016 at 14:45
  • 1
    Frustating is to see people who don't care to invest a minimum effort on research Commented Jul 28, 2016 at 14:50

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 I totally agree with you. In fact, I did clarify that this is not recommended at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.