如何从单独的事件处理程序访问变量

时间:2011-02-13 14:57:04

标签: c# visual-studio-2010 scope

我一直在学校上班,一切都在游泳,直到我遇到困难。我必须编写一个程序,要求用户提供销售人员的初始(C,D或M)以及他们所做的销售价格。我还必须保持每个销售员赚取的佣金的运行记录,直到我清除或退出程序。

当我点击计算佣金时,它当然应该计算佣金(它确实如此),但因为变量是方法级别(或某些较低的访问级别)而且我似乎无法返回它们我可以& #39; t传递第二种方法所需的信息来自" ... C"变量

What the user would hypothetically see if they ran the program

namespace SunshineHotTubs
{
    public partial class FrmSalesCommission : Form
    {
        double cliffS = 0;
        double dinoS = 0;
        double marshaS = 0;

        public FrmSalesCommission()
        {
            InitializeComponent();
        }

        public void btnCalcCommission_Click(object sender, EventArgs e)
        {
            string salesperson = txtInitial.Text;
            double sale = Convert.ToDouble(txtSaleTotal.Text);

            switch(salesperson)
            {
                case "c":
                case "C":
                    cliffS += sale;
                    double cliffC = cliffS * .10;
                    lblCommission.Text = Convert.ToString(cliffC);
                    break;
                case "d":
                case "D":
                    dinoS += sale;
                    double dinoC = dinoS * .10;
                    lblCommission.Text = Convert.ToString(dinoC);
                    break;
                case "m":
                case "M":
                    marshaS += sale;
                    double marshaC = marshaS * .10;
                    lblCommission.Text = Convert.ToString(marshaC);
                    break;
            }
        }

        private void btnDisplayCommission_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Cliff's Commission: " + cliffC + "\n"
                            + "Dino's Commission: " , "Total Commissions");
        }
    }
}

对我来说,获取btnDisplayCommission_Click事件所需信息的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

您已在类级别声明变量:

double cliffC = 0;
double dinoC = 0;
double marshaC = 0;

只需替换它:

double cliffC = cliffS * .10;
double dinoC = dinoS * .10;
double marshaC = marshaS * .10;

关于这个:

cliffC = cliffS * .10;
dinoC = dinoS * .10;
marshaC = marshaS * .10;

<强>更新

您也可以在btnDisplayCommission_Click方法中计算值:

MessageBox.Show("Cliff's Commission: " + cliffS * .10 + "\n"
                + "Dino's Commission: " , "Total Commissions");