在button1中的LIST <double>中调用LIST <double>

时间:2018-10-16 13:44:43

标签: c# buttonclick

我的C#Windows窗体应用程序中有两个按钮。 Button1和Button2。 我想使用在Button1事件中计算出的变量和列表作为Button2事件中的输入变量。我怎样才能做到这一点?示例:

private void button1_Click(object sender, EventArgs e) 
{
   int a;
   // some steps 
   // after these steps, assume a gets the value of 5 so a = 5 at this point.
// also there is a list which gets its values after these steps
List<double> parameterValues = new List<double> { 
                i.GetDouble(), S.GetDouble(), L.GetDouble(),B.GetDouble()                   
};
}

这是button2事件的代码,在此,我希望能够使用在button1的代码中计算出的值。

private void button2_Click(object sender, EventArgs e) 
{
   int b = a + 5;
// some code to call the list as well
}

2 个答案:

答案 0 :(得分:0)

您必须将int设为全局,才能在两个按钮中使用它。

public int a;

private void button1_Click(object sender, EventArgs e) 
{
  a = 5;
// some steps 
// after these steps, assume a gets the value of 5 so a = 5 at this point.
}



private void button2_Click(object sender, EventArgs e) 
{
   int b = a + 5;
}

答案 1 :(得分:0)

您当前遇到范围问题。要在按钮单击2内使用的值必须至少与forms类模块化,以便在两种方法中都可以使用。在此示例中,“ outerValue”是模块化的,并且两者均可访问。通读这篇文章,以更好地了解变量范围。

https://msdn.microsoft.com/en-us/library/ms973875.aspx

public partial class Form1 : Form
{
    private int outerValue = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        int a = 5;
        outerValue = a + 5;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        int b = outerValue + 5;
    }
}