If you debug your code, the problem will become obvious:
val += sb.Append(it.Value + ',');
For each checked item, you:
- Take the value of the checked item, and append a comma;
- Append the value and comma to the
StringBuilder
; - Convert the
StringBuilder
to a String
, and append it to the val
;
So, if you've checked "1", "2" and "3":
- sb: "1,";
val: "1," - sb: "1,2,";
val: "1," + "1,2," = "1,1,2,"; - sb: "1,2,3,";
val: "1,1,2," + "1,2,3," = "1,1,2,1,2,3,";
Use the code that Karthik posted in
Solution #2[
^] to get the correct result.