c# - Loop through checkbox dynamically to check it is true or not -
i have 37 checkboxes on form. have kept each check box names like: p1 p2 p3 ......... p36 p37. in vb.net use loop through controls doint string control casting , values of checkboxes.
the below vb.net code, use , works.
dim start integer = 0 dim stradd string = "" integer = 1 37 const chk string = "p" dim chkbox checkbox = ctype(per_box.controls(chk & i), checkbox) if chkbox.checked = true if start = 0 stradd = stradd + "1" start = 1 else stradd = stradd + ":1" end if else if start = 0 stradd = stradd + "0" start = 1 else stradd = stradd + ":0" end if end if next however, while creating c# application, tried same, not working. can help.
this c# code:
string chk = "p"; int start = 1; string str = ""; (int = 1; <= 37; i++) { chk = chk + i; checkbox chkbox = (checkbox)tab_patients.controls[chk + i]; if (chkbox.checked == true) { if (start == 1) { str = str + "1"; start = 0; } else { str = str + ":1"; } } else { if (start == 1) { str = str + "0"; start = 0; } else { str = str + ":0"; } } }
remove line
chk = chk + i; because when this, chk becomes chk1 first iteration , access controls through controls array this:
checkbox chkbox = (checkbox)tab_patients.controls[chk + i]; you doing this:
checkbox chkbox = (checkbox)tab_patients.controls[chk11]; luckily, have chk11, might working first iteration.
now see happens in next iteration,
for next iteration, chk, has value chk1, chk+i i.e. chk12 , again append 1 more in .controls, hence chk value becomes chk122
checkbox chkbox = (checkbox)tab_patients.controls[chk122]; which nothing, hence not working. , on
you shouldn't modifying chk value. use inside controls, not assign value it.
also in vb doing this:
if chkbox.checked = true if start = 0 stradd = stradd + "1" start = 1 else stradd = stradd + ":1" end if and in c# doing this:
if (chkbox.checked == true) { if (start == 1) { str = str + "1"; start = 0; } else { str = str + ":1"; } } the 2 logics slighty different. comparing 0 in vb , if true, append 1, in c# comparing 1 , if true append 1
Comments
Post a Comment