Use a form int variable in another form C#

Asked

Viewed 54 times

1

I have been trying to use my Form1 double money variable in form2, because I need the amount received in Form1 in form2, I left the publish variable and tried to instantiate but still giving error: code on Form1

public partial class Form1 : Form
{
   public double dinheiro = 0;
  public  Boolean jogar = false;
    public Form1()
    {

        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        bnjogar.Visible = false;
        label4.Visible = false;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        dinheiro = 1.75;
         String i = Convert.ToString(dinheiro);


        Dinheira.Text = "$" + dinheiro;
        jogar = true;
        if(jogar == true)
        {
            bnjogar.Visible = true;
            label4.Visible = true;
        }





    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form3 form3 = new Form3();
        form3.ShowDialog();

    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.Show();

        this.Hide();
    }
}

}

and in form2 this so

public partial class Form2 : Form
{
    int dinheiro2;
    Form1 meuform = new Form1();
    public Form2()

    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {

         dinheiro2 = meuform.dinheiro;  
    }
}

}

If anyone can help me please

  • Within form2 it is not necessary to create an instance of Form1, what you did was create another Form1 other than Form1 that called form2. I’ll go straight to the point, pass the value of the variable money per parameter that will solve your problem. Ex: public Form2(int money) { mone2 = money} private void button1_Click_1(Object Sender, Eventargs e) { Form2 form2 = new Form2(cash); form2.Show(); this.Hide(); }

1 answer

0


You can do it in many ways.

One of them is to pass the values in your form constructor:

//Isso você faz no Form1
private void button1_Click_1(object sender, EventArgs e)
{
    //Aqui você constrói o form passando o valor por parâmetro 
    new Form2(dinheiro).Show();
}

//Isso é no Form2
public Form2(double valor)
{
    //Aqui você pode pegar o valor e armazenar em outro lugar
    InitializeComponent();            
}

Can do searching directly from your Form1:

//Isso é no Form1
private void button1_Click_1(object sender, EventArgs e)
{
    //Aqui você diz que o form1 é o "dono" desse form2
    new Form2().Show(this);
}

//Isso é no Form2
protected override void OnShown(EventArgs e)
{
    base.OnShown(e); 

    //Aqui o Owner é o form1, você pode fazer Cast para ele e acessar o que precisa
    //Funciona também em outros métodos do form2
    var dinheiro = (Owner as Form1)?.dinheiro;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.