0

I have three colored CheckBoxes. Each checkbox should be marked by checking. But when I move the mouse over the checkboxes, all checkboxes are selected in a monotonous color. How should I change the code (see below)? Thanks in advance!

private CheckBox[] checkboxes;

private void Form5_Load(object sender, EventArgs e)
{
   checkboxes = new[] {checkBox1, checkBox2, checkBox3 };

   foreach(var CK in checkboxes)
   {
     CK.Paint += new PaintEventHandler(CK_Paint);
   }
}

private void CK_Paint(object sender, PaintEventArgs e)
{
   if (checkBox1.Checked)
   {
       e.Graphics.FillRectangle(Brushes.Red, 0, 0, 13, 13);
   }
   if (checkBox2.Checked)
   {
      e.Graphics.FillRectangle(Brushes.Green, 0, 0, 13, 13);
   }
   if (checkBox3.Checked)
   {
      e.Graphics.FillRectangle(Brushes.Yellow, 0, 0, 13, 13);
            
   }

}


Mike19
  • 95
  • 6
  • Try using a local variable in foreach loop. foreach(var CK in checkboxes) { CheckBox local=CK; local.Paint += new PaintEventHandler(CK_Paint); } If it solves your problem take a look at this article for more information: https://stackoverflow.com/questions/428617/what-are-closures-in-net – Ali Ihsan Elmas Mar 13 '21 at 16:46
  • Would it not be easier to use a mouse hover event and set the background color? – Caius Jard Mar 13 '21 at 17:15
  • Alternatively, the `sender` argument is the actual checkbox that raised the event so maybe you could just cast sender to a checkbox and do whatever with it – Caius Jard Mar 13 '21 at 17:16
  • I do not think you want to use the “CheckBoxes” `Paint` event for this. This event will fire often like when the user simply hovers over a check box. So, the checked state of the check box will obviously NOT change in that situation. Therefore, calling the code is unnecessary. I would think that the combo boxes `CheckedChanged` event would be more appropriate. – JohnG Mar 13 '21 at 17:27
  • Unfortunately the local variable is not working well. Thanks for your advice " Ali Ihsan Elmas" – Mike19 Mar 13 '21 at 20:02
  • Perhaps it might helb, but i want to checking the checkboxes. Thank you for your information "Caius Jard". And please see my comments further below. – Mike19 Mar 13 '21 at 20:04
  • An interesting approach " Caius Jard". Do you think something like this: foreach(Control c in this.Controls { if(c is CheckBox) { if(((CheckBox)c).Checked == true) // do something}} ?? – Mike19 Mar 13 '21 at 20:06
  • I think you are right, "John G". The event will fire often when the user simply hovers the checkboxes. Thank you for pointing that out. If use of following code: private void CheckBox1_Paint(object sender, PaintEventArgs e) { if (checkBox1.Checked) { e.Graphics.FillRectangle(Brushes.Red,0,0,13,13);}} This works for me. Actually, my intention was to get a compact representation of the code. – Mike19 Mar 13 '21 at 20:10

0 Answers0