-6

I have 30 checkboxes (cb1, cb2,... ,cb30) that I need to be checked programmatically based on a variable value. So, when the var value is 12, I need the checkbox1 to checkbox12 to be .checked = true;

I really have no Idea how to get it work Please help

Thank you

Edit: I tried aghilpro's suggestion but I got errors:

        reader1.Read();
        if (reader1.IsDBNull(0))
        {
            label5.Text = "Nothing yet";
        }
        else
        {
            label5.Text = reader1.GetString(0).ToString() + " Times";
            {
                for (int i = 0; i < reader1.GetInt32(0); i++)
                {
                    Controls["checkBox" + i.ToString()].Checked = True;
                }
            }
        }
        koneksi.Close();

Here's the output:

Error   1   'System.Windows.Forms.Control' does not contain a definition for 'Checked' and no extension method 'Checked' accepting a first argument of type 'System.Windows.Forms.Control' could be found (are you missing a using directive or an assembly reference?)
Andre Rio
  • 3
  • 2

2 Answers2

1

You need to cast the Control to a CheckBox. Hint: Not all controls have a Checked property. I hope this make sense. One question to ask yourself is the following. What would happen if you had a button called "checkBox9"?

var checkBox = (CheckBox)(Controls["checkBox" + i.ToString()]);
checkBox.Checked = True;
vidstige
  • 12,492
  • 9
  • 66
  • 110
  • 1
    As described in your answer, I would use (Controls["checkBox" + i.ToString()]) as Checkbox to avoid issues if e.g. a button is named "checkbox9". A null-check is required to handle/ignore the button. – Odrai Sep 23 '17 at 08:19
1

The answer of vidstige is correct, but I would use the 'as' operator.

The 'as' operator is like a cast operation. However, if the conversion isn't possible, 'as' returns null instead of raising an exception.

CheckBox checkBox = (Controls["checkBox" + i.ToString()]) as CheckBox;
if(checkBox != null)
{
   checkBox.Checked = True;
}
Odrai
  • 2,163
  • 2
  • 31
  • 62