Search code examples
c#asp.netcheckboxlist

How to find what item exaclty checked in CheckBoxList


I have 2 side-by-side CheckBoxList. My purpose is when I check one item in List1, I add that item to the second list. Below is the code I have written.

The problem is it always adds the first item I selected.

protected void lbxSource_SelectedIndexChanged(object sender, EventArgs e)
{
    ListItem itm = lbxSource.SelectedItem;
    ListItem newItem = new ListItem(itm.Text, itm.Value);
    lbTrg.Items.Add(newItem);
}

Actually in the event, I don't know how to get what item I checked last time.


Solution

  • If after adding the item to the second list, you clear selected items in the first list, the next time you get the exact checked item in the event.

    protected void lbxSource_SelectedIndexChanged(object sender, EventArgs e)
    {
        ListItem itm = lbxSource.SelectedItem;
        ListItem newItem = new ListItem(itm.Text, itm.Value);
        lbTrg.Items.Add(newItem);
        lbxSource.ClearSelection(); // This line is the answer to your question
    }
    

    Hope this helps. I had exactly the same case a few weeks ago :)