-1

I am making a sudoku game on C# .NET desktop.

The sudokupanel consists of 81 labels. I define their number on the board with a algorithm.

Now what I want to do is basically this:

foreach(Label l in panel1.Controls.OfType<Label>())
{
    if(l.MouseEnter == true)
    {
        l.ForeColor = Color.White;
    }
}

But it doesn't work. Are there any solutions for this? Sorry I don't know how to use events in if statements.

EDIT: I've decided to just use the event MouseEnter for every label one by one. I know that CS 8.0 should support using events inside foreach stuff but not sure.

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • 1
    `I don't know how to use events in if statements` - you're not supposed to. Events exist specifically to avoid constantly looping to see if a condition has been met. Each of the 81 labels has the mouse enter event. Assign them all with the same event handler which sets its `sender`'s color to white. – GSerg Jan 21 '22 at 07:32
  • 1
    Tag the question with the GUI technology used, winforms or wpf or whatever. – Bent Tranberg Jan 21 '22 at 07:35
  • @BentTranberg Sorry I forgot it. It's winforms. – Kristo Tänak Jan 21 '22 at 07:38
  • 2
    "I know that CS 8.0 should support using events inside foreach stuff but not sure." - No, they do not. – Enigmativity Jan 21 '22 at 07:50
  • I trust that you have created the 81 labels programmatically? If so, you could easily set up the `MouseEnter` and `MouseLeave` event handlers at the same time. – Enigmativity Jan 21 '22 at 07:51

2 Answers2

1

It's not intended to be used this way.

You should subscribe to the MouseEnter event for each label, you can use the same event handler method for all of them and use sender property to know the activated label. You can subscribe directly in VS Properties window if the label are created with the designer, or you can do it programmatically using the += operator.

Please see https://learn.microsoft.com/en-us/dotnet/standard/events/ or any online tutorial about events.

AFract
  • 8,868
  • 6
  • 48
  • 70
1

events are things that tell you when something has happened. They do not tell you the state of something. So there are a few options

Attach an event to each label for entering/leaving the label. You can use the same eventhandler/method to handle the events for each label, and cast the sender object to your label and set the color. Something like this. Note that this should be run once, in the constructor.

foreach(Label l in panel1.Controls.OfType<Label>())
{
    l.MouseEnter += (o, e) => ((Label)o).ForeColor = Color.White;
    l.MouseLeave += (o, e) => ((Label)o).ForeColor = Color.Black;
}

Or you could use a loop that checks the mouse cursor position and check if this is inside each label. But you would have to run the loop for the colors to change, and running it all the time would be wasteful of CPU resources.

JonasH
  • 28,608
  • 2
  • 10
  • 23