需要实现C#计数器

时间:2009-08-30 14:01:11

标签: c# counter

我想制作增量和减量计数器。 有两个按钮叫X和Y.如果先按X然后按Y计数器应该递增。 如果先按Y然后按X计数器应该递减。

我对c#不熟悉。所以有人可以帮我吗? :(

3 个答案:

答案 0 :(得分:3)

听起来你需要2个变量:一个计数器,按下最后一个按钮。我假设这是一个WinForms应用程序,因为你在我写这篇文章时没有指定。

class MyForm : Form
{
    // From the designer code:
    Button btnX;
    Button btnY;

    void InitializeComponent()
    {
        ...
        btnX.Clicked += btnX_Clicked;
        btnY.Clicked += btnY_Clicked;
        ...
    }

    Button btnLastPressed = null;
    int counter = 0;

    void btnX_Clicked(object source, EventArgs e)
    {
        if (btnLastPressed == btnY)
        {
            // button Y was pressed first, so decrement the counter
            --counter;
            // reset the state for the next button press
            btnLastPressed = null;
        }
        else
        {
            btnLastPressed = btnX;
        }
    }

    void btnY_Clicked(object source, EventArgs e)
    {
        if (btnLastPressed == btnX)
        {
            // button X was pressed first, so increment the counter
            ++counter;
            // reset the state for the next button press
            btnLastPressed = null;
        }
        else
        {
            btnLastPressed = btnY;
        }
    }
}

答案 1 :(得分:1)

您可能希望拥有一个您想要跟踪计数器的变量。

int counter = 0;

如果是Web应用程序,那么您必须将其存储在诸如会话状态之类的位置。 然后在增量计数器按钮中:

counter++;

并在你的减量计数器按钮中执行以下操作:

counter--;

答案 2 :(得分:0)

在另一个网站上找到了这个:

public partial class Form1 : Form
{
        //create a global private integer 
        private int number;

        public Form1()
        {
            InitializeComponent();
            //Intialize the variable to 0
            number = 0;
            //Probably a good idea to intialize the label to 0 as well
            numberLabel.Text = number.ToString();
        }
        private void Xbutton_Click(object sender, EventArgs e)
        {
            //On a X Button click increment the number
            number++;
            //Update the label. Convert the number to a string
            numberLabel.Text = number.ToString();
        }
        private void Ybutton_Click(object sender, EventArgs e)
        {
            //If number is less than or equal to 0 pop up a message box
            if (number <= 0)
            {
                MessageBox.Show("Cannot decrement anymore. Value will be  
                                                negative");
            }
            else
            {
                //decrement the number
                number--;
                numberLabel.Text = number.ToString();
            }
        }
    }