Son Gozita
Son Gozita

Reputation: 67

Accessing other forms value

I have 2 forms namely, Form1 & Form2.

In Form1 I have a String named "HumanName", this "HumanName" has a value which is from a textbox.text. Also i have button named Button1.

In Form2 I has a label named Label1.

This is what I want to accomplish. When I hit/press Button1, the Label1.Text=HumanName

Form1:

HumanName = textbox.text, Button1

Form2:

Label1.Text = HumanName

here is my code:

public partial class Form1 : Form
{
    private void PersonalInformationToForm2()
    {
        HumanName = textBox_Name.Text;
    }

    private void Button1_Click(object sender, EventArgs e)
    {           
        PersonalInformationToForm2();
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();

        Label1.Text=HumanName;   //I need the value of HumanName from Form1        
    }
}

Upvotes: 1

Views: 109

Answers (4)

Lotok
Lotok

Reputation: 4607

On Form1 encapsulate the control in a Property

public string GetTextboxText {get{ return Textbox1.Text;}}

On the other form

var formOne = (Form1)Application.OpenForms["Form1"];
Label1.Text = formOne.GetTextboxText;

Upvotes: 1

JvRossum
JvRossum

Reputation: 1008

Create an instance for Form1 which is accessible for Form2 you can do it like this:

public static Form2 Instance;

public Form2()
{
     InitializeComponent();
     Instance = this;
}

Set the modifier for Label1 to true in the properties.

When hitting that button1 on Form1 do this:

private void Button1_OnClick(object sender, EventArgs args)
{
    Form2.Instance.Label1.Text = textBox1.Text;
}

Upvotes: 0

himadri
himadri

Reputation: 638

in Form2 create a constructor in the following way

public void Form2(string name)
{
  Label1.Text=name;
}

Noe from Form1 we can send the value in the following way

string HumanName=textbox.text;
Form2 frm2=new Form2(HumanName);
frm2.Show();

Upvotes: 0

Antony Koch
Antony Koch

Reputation: 2053

Create a constructor for Form2 which takes the HumanName.

Then upon button press in Form1, create a new instance of the form and pass in Textbox1.Text

Upvotes: 0

Related Questions