Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send variables from one button to another

Tags:

c#

I have this so far on one of my programs and I would like it to be where if you press on one button to break up the number you enter, you enable another button to get that data and save it to an outfile.

private void button1_Click(object sender, EventArgs e)
{
    string number = textBox1.Text;
    int digits = int.Parse(number);
    if (digits > 9999 || digits < 0)
    {
        MessageBox.Show("That is not a valid number");
    }
    else
    {
        int thousands = digits / 1000;
        int hundreds = (digits - (thousands * 1000)) / 100;
        int tens = (digits - ((hundreds * 100) + (thousands * 1000))) / 10;
        int ones = (digits - ((tens * 10) + (hundreds * 100) + (thousands * 1000))) / 1;
        label6.Text = thousands.ToString();
        label7.Text = hundreds.ToString();
        label8.Text = tens.ToString();
        label9.Text = ones.ToString();
        button2.Enabled = true;
    }

I have this so far and it works but for button2, I want these variables that are generated from clicking button one to pass to button2 so when you click on it, it will use those variables to write to a file. Any ideas?

like image 540
Skynet Avatar asked Nov 17 '25 17:11

Skynet


2 Answers

There are several ways, but looking at what you already have, why not just reread the labels back into the variables you want?

private void button2_Click(object sender, EventArgs e)
{
    int thousands = Convert.ToInt32(label6.Text);
    int hundreds = Convert.ToInt32(label7.Text);
    //...etc
}

You could also just set globals instead of locals, ie declare your ints outside of any method call

int thousands;
int hundreds;
int tens;
int ones;
private void button1_Click(object sender, EventArgs e)
{
    //...code
    thousands = digits / 1000;
    hundreds = (digits - (thousands * 1000)) / 100;
    tens = (digits - ((hundreds * 100) + (thousands * 1000))) / 10;
    ones = (digits - ((tens * 10) + (hundreds * 100) + (thousands * 1000))) / 1;
}
private void button2_Click(object sender, EventArgs e)
{
    Console.WriteLine(thousands); //...etc
}

Don't do this too often as if you have tons of globals things can get confusing quick, but for a simple program (which this seems to be) it should be ok.

like image 91
Kevin DiTraglia Avatar answered Nov 19 '25 06:11

Kevin DiTraglia


if it is a asp.net webforms application you can save the vars in the view state and retrieve them from the other button click

//setting
ViewState["thousands "] = thousands;

//Reading
int thousands = Convert.ToInt32(ViewState["thousands "]);

if it is console, windows app, windows service ou can just declare the int vars outside the event scope and you would be able to access them from both button click event;

like image 30
RollRoll Avatar answered Nov 19 '25 05:11

RollRoll