tags:

views:

364

answers:

2

I want to make increment and decrement counter. There are two buttons called X and Y. If first press X and then press Y counter should increment. If first press Y and then press X counter should decrement.

I am not familiar with c#. So can anyone help me please ?? :(

A: 

You would want to have a variable that you want to keep track of the counter.

int counter = 0;

If it is a web application then you must store this some where such as session state. then in your increment counter button:

counter++;

and in your decrement counter button do this:

counter--;
Roberto Sebestyen
+3  A: 

Sounds like you need 2 variables: a counter, and the last button pressed. I'll assume this is a WinForms application, since you did not specify at the time I am writing this.

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;
        }
    }
}
Paul Williams