locked
Casting exception for CheckBox when accessing subcontrols RRS feed

  • Question

  • User1596584848 posted

    I have a custom control which is supposed to be able to put a check box set on a page in my oninit method.

    String[] options = ListString.Split(',');
                    for (int i = 0; i < options.Length; i++)
                    {
                        CheckBox aCheckBox = new CheckBox();
                        aCheckBox.Text = options[i];
                        fieldset.Controls.Add(aCheckBox);
                    }

    this.controls.add(fieldset)

    Yet when I have the custom control on an aspx page and need to iterate through it in the codebehind, I get a class casting exception. Why can't a control be cast as a checkbox in my case?

    dim ci

    dim castCi As CheckBox

    For Each ci In someCheckList.fieldset.controls
                castCi = CType(ci, CheckBox)
                If castCi.Checked Then
                    strContent = strContent & castCi.Text & " "
                End If
            Next

    Edit: Nevermind, I had a legend control in there, I didn't check for.

    Friday, December 2, 2011 2:17 PM

All replies

  • User185651982 posted
    For Each ci In someCheckList.fieldset.controls
        if (ci.GetType() = typeof(CheckBox) Then
           
                castCi = CType(ci, CheckBox)
                If castCi.Checked Then
                    strContent = strContent & castCi.Text & " "
                End If
        End if
    Next

    Usually in situations like this I check the type of the control. Something like

     

     

    Friday, December 9, 2011 7:01 PM