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.
James AxsomPosted Aug 27, 2018, 4:02 PM
You asked, “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 employees can use. Surely the best practice is not to repeat code 32 times which we all know?”
If I were to read your question without the code sample below I would interpret your question as, “How do I create 32 instances of my TowColorButton Class without declaring 32 object variables, instantiating those object variables and setting their properties to define where they show up on the form”
That just can’t be what you are asking because your code sample is asking,
private void O16_Click(object sender, EventArgs e)
{
////What do I put here?
}
So, the real question must be, how do I create 32 click implementations only once.
Answer: Use an interface. Pass in a value to a context class telling the factory which implementation use.
Here is a hypothetical abstract pseudo code to get the idea of what I speak of:
Chris JohnsonPosted Aug 28, 2018, 1:31 AM
Željko PerićPosted Aug 25, 2018, 12:00 PM