Shoxxer Shoxxer - 1 month ago 7
C# Question

Sending values between Windows forms

I'm working on a project where I want to send values between forms, however I ran into a problem.

Form 1:

public Vägval(string name, string gender, int gold)
{


InitializeComponent();
ChoosePicture(gender);
tname.Text = name;
string Namn = name;
string Gender = gender;
int Gold = gold;
tMynt.Text = gold.ToString();
tLife.Text = 5.ToString();
Skattkista skatt = new Skattkista(Namn, Gender, Gold);


}


When picture is clicked I wanna open the second Form and send three values with it: Name, Gender and gold.

private void pictureBox1_Click(object sender, EventArgs e)
{
Skattkista skatt = new Skattkista(Namn, Gender, Gold);
skatt.Show();
}


But I get error here:


The name 'Namn' does not exist in the current context

The name 'Gender' does not exist in the current context

The name 'Gold'does not exist in the current context


I tried putting the
Skattkista skatt = new Skattkista(Namn, Gender, Gold);
on the constructor but then I cant open the form when the picture is clicked.

All I want is to open a new form and send three values with it when the picture is clicked

Joe Joe
Answer

It looks as though your variables might have a local scope to the method you created them in and not a global scope to the form itself. I cannot tell without more code. One suggestion would be to try giving each form global properties

public string Namn {get; set;}
public string Gender {get; set;}
public int Gold {get; set;}

Your Constructor should then look like this

public Vägval(string name, string gender, int gold)
    {
        InitializeComponent();
        ChoosePicture(gender);

        //assigns all the properties
        this.Namn = name;
        this.Gender = gender;
        this.Gold = gold;

        //Set GUI 
        tname.Text = name;
        tMynt.Text = gold.ToString();
        tLife.Text = 5.ToString();
    }

The Click Event

 private void pictureBox1_Click(object sender, EventArgs e)
    {
        //Create new form object using Vagval properties and show it
        Skattkista skatt = new Skattkista(this.Namn, this.Gender, this.Gold);
        skatt.Show();
    }