C# – ASP.NET: Problem with CheckBoxList and OnSelectedIndexChanged

asp.netc

I'm having a problem with CheckBoxList and OnSelectedIndexChanged:

            <asp:UpdatePanel runat="server">
                <ContentTemplate>

                     <asp:CheckBoxList 
                        id="lstWatchEType" 
                        runat="server" 
                        DataTextField="DescriptionText" 
                        DataValueField="Id"
                        AutoPostBack="true"
                        OnSelectedIndexChanged="lstWatchEType_SelectedIndexChanged"/>

                </ContentTemplate>
            </asp:UpdatePanel>

This is populated in Page_Load (!IsPostBack)

public static void PopulateWatchEType(CheckBoxList list, Guid clientId)
        {
            OffertaDataContext db = new OffertaDataContext();

            var ds = (from e in db.EnquiryTypes select new {
                Id = e.Id,
                DescriptionText = e.DescriptionText,
                IsWatching = !db.WatchXrefEnquiryTypes.Any(f => f.ClientId.Equals(clientId) && f.EnquiryTypeId==e.Id && f.Inbox==false)
            });

            list.DataSource = ds;
            list.DataBind();

            foreach(var item in ds)
            {
                list.Items.FindByValue(item.Id.ToString()).Selected = item.IsWatching;
            }
        }

My problem is in:

 protected void lstWatchEType_SelectedIndexChanged(Object sender, EventArgs e)
    {
        ListItem item = lstWatchEType.SelectedItem;
        ...
    }

Where item is always the first element in the list???

Best Answer

The selected item property will return the selected item with the lowest index inside of the list. If the first item is selected, then it will return the first item.

To get the latest selected item, perhaps you can create a global variable and set that variable on index changed. You can create a ListItem collection that first holds all of the initial selected indexes like Kirtan suggested, then create a new collection that holds all of the newest selections whenever the selected index changes. Match the two lists, and whatever item is in the new list that is not in the older list is your latest selected index.

Hope this helps.

Related Topic