Windows Forms - how to exclude a button from the whole set
I have Windows Form
one that contains only buttons
. The end goal is to make a simple logic game that I saw, but at the moment the problem is that I want to do different actions when the button is clicked New
, but now it is part of everything buttons
in the form, so sometimes the action on it is also is executed, which should not be. To make sure I have two screenshots:
So this is how I want it to be - I have a matrix - 3x3 (in which case it could be NxN
). By clicking New
, I want to be able to do different things, one of which is to make the buttons N
colored red. What's happening now, sometimes my button New
gets colored as well because I view buttons like this:
foreach (Control c in this.Controls)
{
if (c is Button)
{
...
and hence are sometimes New
selected too, so I get this:
What I am currently thinking is to just do the check when I need to in the code and explicitly exclude my button New
, but I don't think this is a good way because I might end up with code doing this thing in many places in my program, so what is the correct solution in this case? If you need any code, please ask.
source to share
Instead of looping through the controls, add all the matrix buttons to the list and highlight the button new
:
private Button[] buttons;
private Button newButton;
Now you can add as many buttons as you like:
for (int i = 0; i < 9; i++)
{
buttons[i] = new Button();
buttons[i].Text = "Button" + i;
Controls.Add(buttons[i])
}
And finally, your button new
will go through buttons
:
private void newButton_Click(object sender, EventArgs e)
{
foreach (Button b in buttons)
{
...
}
}
You can inherit from the button class. Create your own button, use this control (which will have the same functionality as the parent) to set, and test it as you iterate over the controls.
You can also use the Tag property for this fill, but I think inheritance will be clearer by adding semantic meaning to your code.
source to share