2

How can I add CheckBoxList Item on String Builder.

CheckBoxList cblItem = new CheckBoxList();
cblItem.ID = "cblItem";

var MainCatGroup = subCatDet.GroupBy(q => q.catCode).Select(q => new { CatName = q.Key, Items = q.ToArray() }).Select(q => new { CatName = q.CatName, Items = q.Items.OrderBy(t => t.catCode).ToArray() }).ToArray();
foreach (var mainCat in MainCatGroup)
{
    sb.Append(string.Format("<li><a href=\"javascript:void(0)\">{0}</a>", mainCat.CatName.ToString()));
    sb.Append(string.Format("<ul>"));

    foreach (var item in mainCat.Items)
    {
        string Subcat = item.subCat.ToString();
        string catCode= item.catCode.ToString();
        sb.Append(string.Format("<li>"));
----->  sb.Append(string.Format(cblItem.Items.Add(new ListItem("{0},{1}")), Subcat, catCode));     <----
        sb.Append(string.Format("</li>"))
     }
        litList.Text = sb.ToString();
    }

So, How can i edit below the line?

sb.Append(string.Format(cblItem.Items.Add(new ListItem("{0},{1}")), Subcat, catCode));
Mafii
  • 7,227
  • 1
  • 35
  • 55
ekrem tapan
  • 147
  • 4
  • 15
  • 3
    Its not clear what you are asking. – Yacoub Massad Apr 26 '16 at 08:47
  • @YacoubMassad when i use stringbuilder add dynamically item on the checkboxlist, i have a error on the line. so i dont know its logical problem or another – ekrem tapan Apr 26 '16 at 08:48
  • 2
    But what are you trying to do? Please give more context. – Yacoub Massad Apr 26 '16 at 08:49
  • @ekrem-tapan StringBuilder can't be used to add dynamically items in CheckBoxList. StringBuilder can build a message which you can later add to the list. Are you trying to add the same string to the list and to StringBuilder? – Michał J. Gąsior Apr 26 '16 at 08:53
  • Yes, I'm pretty sure. :) StringBuilder is to avoid multiple string creation (string is an immutable type). [Here you can learn more about StringBuilder purpose.](http://stackoverflow.com/questions/2365272/why-net-string-is-immutable) – Michał J. Gąsior Apr 26 '16 at 08:57
  • @mikes u have a any solution for this problem ? – ekrem tapan Apr 26 '16 at 09:00

1 Answers1

1

You probably want to do something like this instead:

cblItem.Items.Add(new ListItem(sb.ToString()), Subcat, catCode);

Or better:

cblItem.Items.Add(new ListItem(string.Format("{0},{1}", Subcat, catCode));

You also souldn't mix naming convetions. The Subcat and MainCatGroup local variables shouldn't be named starting upper case letter.

And in the and you can also try StringFormat.AppendFormat (more details here):

sb.AppendFormat("2) {0}, {1}", var1, var2);
Michał J. Gąsior
  • 1,457
  • 3
  • 21
  • 39