Home > Software engineering >  Get value from another tabpage
Get value from another tabpage

Time:10-14

i'm currently having a problem getting value from another tab page in windows form using c#. I have tabPage1 and tabPage 2 inside tabControl. I want to use the value I have saved in tabpage1 for another calculation in tabPage 2 but I can't find a way to do this. Here is an example of what i want for further understanding my question. Please anyone help me fix this, thank you.

 private void button1_Click_1(object sender, EventArgs e)
 {
            double age = Convert.ToDouble(richTextBox1.Text);
 }

private void button2_Click(object sender, EventArgs e)
 {          double a=0;
            for (int i=1,i<age,i  )
        {
            a=a i;
        }
 }

P.s. button1 is in tabPage1 and button2 is in tabPage 2

CodePudding user response:

This is an issue with variable scoping. In your button2_Click method you are probably getting an error about age not being declared.

There are a few options:

  1. Get the value of age in your button2_Click method again.
private void button2_Click(object sender, EventArgs e)
{
       double a = 0;
       double age = Convert.ToDouble(richTextBox1.Text); // Get value again locally.
       for (int i = 1; i < age; i  )
       {
           a  = 1;
       }
}

This will mean that age is available within the scope of button2_Click.

  1. Store it in a property on the form, making it available to all your methods in that Form.
public partial class Form1 : Form
{
    private int Age { get; set; } // Property that stores age in the class.

    private void button1_Click_1(object sender, EventArgs e)
    {
       Age = Convert.ToDouble(richTextBox1.Text); // Store in property not local var
    }

    private void button2_Click(object sender, EventArgs e)
    {
        double a = 0;
        for (int i = 1; i < Age; i  ) // Loop to property value not local var.
        {
            a  = 1;
        }
    }
}

Which option you choose will depend on your use case (e.g. if pressing button 1 is necessary before pressing button 2, then you will want to go with option 2; but if you could just press button 2 without first pressing button 1 then option 1 would work).

Please note that, in your for loop you have used commas, where you need to use semicolons, my example above correct this.

In addition, as @LarsTech has mentioned, you need to use int.TryParse ideally, as the value in your textbox may not be a number.

  • Related