-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?)
15
  • 1
    please add some html and code for reference.. Commented Sep 23, 2017 at 6:30
  • it's actually in C# Commented Sep 23, 2017 at 6:31
  • 2
    What have you tried so far? Have a look at the tour (stackoverflow.com/tour) and How to Ask Commented Sep 23, 2017 at 6:31
  • winforms or asp? add your code first Commented Sep 23, 2017 at 6:32
  • 1
    Yes, but still you will have some html where check box are binding and you will also have method where you need to do this code, so add both for reference.. Commented Sep 23, 2017 at 6:32

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.