StringBuilder sbOccupation = new StringBuilder();
foreach (ListItem li in cblOccupation.Items)
{
if (li.Selected)
{
sbOccupation.Append(li.Text);
sbOccupation.Append(",");
}
}
property.Occupation=sbOccupation.ToString().Remove(sbOccupation.ToString().LastIndexOf(","), 1);
If nothing has been appended to sbOccuption
, then it will be empty - so LastIndexOf(',')
will return -1, which isn't a valid first argument to string.Remove
.
Given that you know it will always be the last character of the result, you could just use:
if (sbOccuptation.Length > 0)
{
// Trim the trailing comma
sbOccupation--;
}
string text = sbOccupation.ToString();
However, it would be simpler just to use string.Join
and LINQ:
// This replaces *all* your code
property.Occupation = string.Join(",", cblOccuptation.Items
.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Text));
If you're using .NET 3.5, you'll need a call to ToArray
after the Select
call, but that's simple enough.
See more on this question at Stackoverflow