Access dynamically created htmlgenericcontrols like div,label and checkbox using c#

315 views Asked by At

I have created some div, label and checkbox using htmlgenericcontrol with runat="server". these dynamically created div is added inside the main div which is created at the design time. Now, i want to access the checkbox which is there inside dynamically created div using c# on page load. my dynamic div created using c# looks like this -

<div id='firstdiv'> 
<div id='seconddiv'>
              <label id='lbl' >
                  <input type="checkbox" id="chk" value="check" runat="server">                                                                          
                  <div id='thirddiv'></div>
              </label>
</div></div>

I tried below options but none of them worked -

HtmlGenericControl chkfirstdiv = HtmlGenericControl)maindiv.FindControl(strchkfirstdiv) as HtmlGenericControl;

HtmlGenericControl chkfirstdiv1 = HtmlGenericControl)FindControl(strchkfirstdiv) as HtmlGenericControl;

LiteralControl literalControl = LiteralControl)maindiv.FindControl(strchkfirstdiv);

Can anyone help in accessing the dynamic checkbox inside dynamic div?

2

There are 2 answers

1
Babak Naffas On

For WebForms, you should create the control as <asp:Checkbox Id="MyCheckbox" runat="server" Text="Check" /> and the designer should generate Checkbox MyCheckbox for you and it's Checked property will be populated on postback without the need to call FindControl(..).

0
ahmednawazbutt On

asp buttons will be accessed based on their names not IDs so place a name attribute inside checkbox definition like <asp:Checkbox Id="MyCheckbox" name="myCheckBox" runat="server" Text="Check" /> and access myCheckBox in backend on click event