Archana B.R
Archana B.R

Reputation: 407

How to avoid duplicate items being added from one CheckBoxList to another CheckBoxList

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

Answers (3)

soumya11101
soumya11101

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

Derek
Derek

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

chris
chris

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

Related Questions