Home > database >  how to display checked state in a loop?
how to display checked state in a loop?

Time:11-22

I'm using this code to make checkboxes visible based on name. But if I use controls I can't check if checkbox is checked(because I want to show checkbox in a checked state).

My code:

 for (int i = 0; i < Program.productOperationCount; i  )
        {
            
            this.Controls.Find($"checkBox{i   1}", true)[0].Visible = true;
        }

I need something like this, but there is no method for it:

this.Controls.Find($"checkBox{i   1}", true)[0].Checked = true;

CodePudding user response:

try like this.

      foreach (var checkBox in this.Controls.OfType<CheckBox>())
        {
            if (checkBox.Checked == true && checkBox.Name =="cbname")
            {
               //do stuff
            }
                
        }

CodePudding user response:

Use a loop to navigate the form controls and a control variable to count the checkbox controls.

int j = 0;
for(int i = 0; i < this.Controls.Count; i  )
{
     if(this.Controls[i] is CheckBox)
     {
         CheckBox chk = (CheckBox)this.Controls.Find($"checkBox{j   1}", true)[0];
         chk.Checked = true;
         j  ;
     }
}

Or

foreach (var ctr in this.Controls)
{
    if (ctr is CheckBox)
    {
        CheckBox chk = (CheckBox)ctr;
        chk.Checked = true;
    }
}

CodePudding user response:

you should make a custom class that contains the object that you want and a bool called _checked. that easy !

A class like :

[System.Serializable]
public class ExampleWithBoolHAHAHAHA
{
    public bool _checked = false;
    public object yourObjectInHere;
}
  • Related