Reputation: 575
I have a check box list item with List items in it. When i save the form selected values should be save to database . See my logic.
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
It is working great but because of the "," which is i am putting between two values they are separated with each other, but at last item also it will append the "," . Is there any way to remove last "," or insert "." at last ","
Is there any logic for doing this?
Upvotes: 0
Views: 663
Reputation: 278
The easiest way is to use String.Join
:
string Type = String.Join(",", chbCourse.Items);
If "." is also required
string Type = String.Concat(String.Join(",", chbCourse.Items),".");
Upvotes: 1
Reputation: 48550
How about
string Type = null;
type = String.Join(",",
chbCourse.Items.Where(Function(x) x => x.Selected)
.Select(Function(y) y => y.ToString()).ToArray);
Upvotes: 0
Reputation: 66479
Join all selected items, using string.Join
and LINQ
:
Type = string.Join(",",
chbCourse.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Text));
Since string.Join
only adds the separator between items, it won't add an extra comma to the end.
(Also, calling ToString() on a ListItem
displays the class type; you have to use the Text
property.)
Upvotes: 4
Reputation: 3834
Do it like this for selected items:
string Type = string.Join(",", CheckBoxList1.Items.Cast<ListItem>().Where(a=>a.Selected).Select(a => a.Text));
if (!string.IsNullOrEmpty(Type)) // To add '.' at end
Type = Type + ".";
Upvotes: 1
Reputation: 30042
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
if(Type != null)
Type = Type.TrimEnd(',');
Try not to use Class Names as variable names.
Upvotes: 0
Reputation: 1403
If I'd wanted to put dot (".") on the last character, then I would do:
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
if (i == chbCourse.Items.Count - 1) Type += chbCourse.Items[i].ToString() + ".";
else
Type += chbCourse.Items[i].ToString() + ",";
}
}
Upvotes: 0
Reputation: 148644
void Main()
{
var a="1,2,3,";
a=a.TrimEnd(new [] {','});
Console.WriteLine (a); //1,2,3
}
Upvotes: 1