如何将变量从一个按钮发送到另一个按钮

时间:2012-09-23 20:07:30

标签: c#

到目前为止,我已经在我的一个程序中使用了这个程序,如果您按下一个按钮来分解您输入的数字,我希望它能够在哪里,您启用另一个按钮来获取该数据并将其保存到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;
    }

到目前为止,我有这个,但是对于button2,我希望通过单击按钮1生成的这些变量传递给button2,因此当您单击它时,它将使用这些变量写入文件。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果是asp.net webforms应用程序,您可以将vars保存在视图状态,并从其他按钮单击检索它们

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

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

如果它是控制台,Windows应用程序,Windows服务,你只需在事件范围之外声明int vars,你就可以从两个按钮点击事件中访问它们;

答案 1 :(得分:1)

有几种方法,但看看你已有的方法,为什么不把标签重新读回你想要的变量呢?

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

您也可以设置全局变量而不是本地变量,即在任何方法调用之外声明您的整数

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
}

不要经常这样做,就像你有大量的全局变量一样,事情可能会让人感到困惑,但对于一个简单的程序(这似乎是这样),它应该没问题。