Reputation: 407
While adding items from one CheckBoxList
to another CheckBoxList
how to check if the item is already present in the second CheckBoxList
using asp.net c#
The code I have written to move between CheckBoxLists
is:
protected void add_Click(object sender, EventArgs e)
{
for (int i = 0; i <= CheckBoxList2.Items.Count - 1; i++)
{
if (CheckBoxList2.Items[i].Selected)
{
CheckBoxList3.Items.Add(CheckBoxList2.Items[i]);
CheckBoxList3.ClearSelection();
}
}
}
I am using add_Click button to move items between lists. I need to validate while adding items.
Kindly help. Thank you..!!
Upvotes: 1
Views: 1865
Reputation: 1
without using a third CheckBoxList..(modified the above ans)
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected)
{
if (!CheckBoxList2.Items.Contains(li))
{
CheckBoxList2.Items.Add(li);
}
}
}
Upvotes: 0
Reputation: 8628
This will work :-
for (int i = 0; i <= CheckBoxList2.Items.Count - 1; i++)
{
if (CheckBoxList2.Items[i].Selected)
{
CheckBoxList4.Items.Add(CheckBoxList2.Items[i].ToString().Trim());
}
}
foreach (ListItem item in CheckBoxList4.Items)
{
if (!CheckBoxList3.Items.Contains(item))
{
CheckBoxList3.Items.Add(item);
}
}
Upvotes: 1
Reputation: 403
quote from another answer by @Joel-Coehoorn:
You need a using directive for System.Linq. .Where() is an extension method on IEnumerable (which IList implements) that is defined in the System.Linq namespace.
first take all the selected items
var checkedItems = CheckBoxList2.Items.Where(i => i.Selected);
and then iterate through.
foreach(var item in checkedItems)
{
if(!CheckBoxList3.Items.Contains(item))
{
CheckBoxList3.Items.Add(item)
}
}
that should be fine.
Upvotes: 3