Search code examples
c#asp.netcheckboxlist

Why does the value in multiple CheckBoxList selected even though I specified one with the ID


I am generating three separate CheckBoxList

C#:

//...
foreach (DataRow dr in dt.Rows)
{
    ListItem li = new ListItem((string)dr["LD"], dr["ID"]+"");
    cl1.Items.Add(li);
    cl2.Items.Add(li);
    cl2.Items.Add(li);
}
//...
SelectCheckBoxList("76", cl2);


private void SelectCheckBoxList(string valueToSelect, CheckBoxList lst)
{
    ListItem listItem = lst.Items.FindByValue(valueToSelect);
    //ListItem listItem = lst.Items.FindByText(valueToSelect);
    if (listItem != null) listItem.Selected = true;
}

ASP.NET:

<asp:CheckBoxList ID="cl1" runat="server" RepeatDirection="Vertical" RepeatLayout="UnorderedList">
</asp:CheckBoxList>
<asp:CheckBoxList ID="cl2" runat="server" RepeatDirection="Vertical" RepeatLayout="UnorderedList">
</asp:CheckBoxList>
<asp:CheckBoxList ID="cl3" runat="server" RepeatDirection="Vertical" RepeatLayout="UnorderedList">
</asp:CheckBoxList>

Since they all have the same value but I only want the value in the CheckBoxList with the ID cl2 selected. However, all three CheckBoxList has the item selected.

How can I resolve this please.


Solution

  • A reference to the same ListItem is added to each list. Add a copy of the ListItem to each list instead:

    foreach (DataRow dr in dt.Rows)
    {
        cl1.Items.Add(new ListItem((string)dr["LD"], dr["ID"]+""));
        cl2.Items.Add(new ListItem((string)dr["LD"], dr["ID"]+""));
        cl2.Items.Add(new ListItem((string)dr["LD"], dr["ID"]+""));
    }