I'm working on a C# project that requires a lot of buttons, but most of the buttons do mostly the same thing, with simple variations on the number to be passed.

Here's what I've done so far:

public void setPieceOne(int x)
        {
            if (pressStartFlag == 0)
            {
                pressStartFlag = 1;
                lastStartValue = startBoard[x];
                startBoard[x] = -1;
                darkStartBoard();
            }
            else if (pressStartFlag == 1)
            {
                pressStartFlag = 0;
                startBoard[x] = lastStartValue;
                lastStartValue = -1;
                lightStartBoard();
            }
        }

The 'pressStartFlag' is merely a flag if the button is pressed. darkStartBoard() is a function to darken the bg color of the button clicked, while lightStartBoard() returns it to it's former state. Now, say I have 21 buttons. What I did was double click each one of them to create the "click event" of each, and then simply called the "setPieceOne(x)" function.

So I have something like this:

private void btnP1_Click(object sender, EventArgs e)
        {
            setPieceOne(0);
        }

repeated 21 times, with variations on the name and the int to be passed. It occurred to me that this might not be the best way to do this.

I wanted to create a function that would be used for all the Button events (via the event list in Object Properties) that could plug in all the necessary details, but I do not know how to detect which of the buttons are pressed.

I'm not sure if this is right:

public void startPcsButton_Click(object sender, EventArgs e)
        {
            Button isButton1 = new Button();
            if (isButton1.Name.ToString() == "btnP1")
                setPieceOne(0);
        }

That returns no errors, but binding it to the "btnP1" click event does nothing. I suppose I need to put either sender, or e in there somewhere.

May I have some advice on this, please? Thanks in advanced for those who will reply.

Nevermind. Got it. :)

public void startPcsButton_Click(object sender, EventArgs e)
        {
            Button isButton1 = (Button) sender;
            if (isButton1.Name.ToString() == "btnP1")
                setPieceOne(0);
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.