c# - Count the number of TextBoxes and CheckBoxes in a form -
my requirement count total number of textbox , checkbox present directly inside form id="form1"
, when user clicks on button 'btngetcount'
. here code have tried doesn't count , counter remains @ zero, though have 3 textboxes , 2 checkboxes in form. however, if remove foreach loop , pass textbox control = new textbox();
instead of present code counts first textbox , counttb returns value one.
protected void btngetcount_click(object sender, eventargs e) { control control = new control(); int countcb = 0; int counttb = 0; foreach (control c in this.controls) { if (control.gettype() == typeof(checkbox)) { countcb++; } else if (control textbox) { counttb++; } } response.write("no of textboxes: " + counttb); response.write("<br>"); response.write("no of checkboxes: " + countcb); }
you must recursively loop through other controls.
<form id="form1" runat="server"> <div> <asp:textbox id="txt" runat="server"></asp:textbox> <asp:checkbox id="cb" runat="server"></asp:checkbox> </div> </form> protected void page_load(object sender, eventargs e) { var controls = form1.controls; var tbcount = 0; var cbcount = 0; countcontrols(ref tbcount, controls, ref cbcount); response.write(tbcount); response.write(cbcount); } private static void countcontrols(ref int tbcount, controlcollection controls, ref int cbcount) { foreach (control wc in controls) { if (wc textbox) tbcount++; else if (wc checkbox) cbcount++; else if(wc.controls.count > 0) countcontrols(ref tbcount, wc.controls, ref cbcount); } }
Comments
Post a Comment