3
Answers

Buttons and Classes. EASY for you brilliant guys.

Chris Johnson

Chris Johnson

6y
497
1
Hi all.
I wonder if someone can advise.
I am writing a new diag program and need help on buttons using a class to change the button forecolor (and apply plc code, that bit is no problem).
I have 32 buttons on a form. The form is for turning on IO's on a PLC which I can do easily. I just want to create a graphical form that other emplyees can use. Surely the best practise is not to repeat code 32 times which we all know?

So below is a small global class I have created. How can I quickly apply this to all 32 buttons on the form?
If someone can give me an example on one button that would be superb.
What do I put in this event?

 private void O16_Click(object sender, EventArgs e)
        {
                 ////What do I put here?
        }

class TwoColorButton : Button
    {
        private int stateCounter = 0;
        private Color[] states = new Color[] { Color.Black, Color.Red };

        public TwoColorButton()
            : base()
        {
            this.BackColor = states[stateCounter];
            this.Click += this.clickHandler;
        }

        protected void clickHandler(object sender, EventArgs e)
        {
            stateCounter = stateCounter == 0 ? 1 : 0;
            this.BackColor = states[stateCounter];
        }
    }

Thanks for your help in advance.
Answers (3)