ASP.NET: problem with CheckBoxList and OnSelectedIndexChanged

I have 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:

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

      

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

0


a source to share


1 answer


The selected item property returns the selected item with the lowest index within the list. If the first item is selected, it will return the first item.

To get the last selected item, perhaps you can create a global variable and set that variable in the index. You can create a ListItem collection that first contains all the original selected indexes, such as the one suggested by Kirtan, and then create a new collection that contains all the newest selections when the selected index changes. Compare the two lists and any item in the new list that is not in the older list is your last selected index.



Hope it helps.

+2


a source







All Articles