locked
Dropdown .Addrange adding same value to dropdown c# RRS feed

  • Question

  • User-501297529 posted

    When I select a different value from the cmbFman dropdown it adds the same value everytime. So if I selected a different name from the cmbFman dropdown I get another duplicate value added to the cmbOSA dropdown. Here is my code I thought .AddRange had something to do with it but when I remove that code I don't get anything in the cmbOSA dropdown. That's probably not surprising.

     private void cmbFman_SelectedIndexChanged(object sender, EventArgs e)
            {
                PopulateDropdown();
            }
            public void PopulateDropdown()
            {
                IQueryable<VECTRENLOCATION> locs = dc.VECTRENLOCATIONs.Where(f => f.INACTIVE != 1 || f.INACTIVE == null || pre_IsLookup);
                if (FormOSAOverride == null || FormOSAOverride == "")
                    locs = locs.Where(f => UserSession.UserLocationList.Contains(f.BILLCODE + "-" + f.COMPANYNUMBER));
                else
                    locs = locs.Where(f => FormOSAOverride.Split(',').Contains(f.id.ToString()));
                loadedOSAs = locs.OrderBy(f => f.OSA).ToList();
                cmbOSA.Items.AddRange(loadedOSAs.ToArray());
            }

    Friday, November 16, 2018 8:25 PM

Answers

  • User1281381861 posted

    Just before "Items.AddRange" you can apply "Contains" to avoid duplicates.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, November 24, 2018 2:43 PM

All replies

  • User475983607 posted

    Items.AddRange() simply appends collection to the current Items.  If an item exists in the Items collection and in the loadedOSAs collection then you'll get duplicates. 

    The general intent of the code and design are not clear.  With that being said, maybe simply disabling ViewState on the dropdown will provide the expected behavior.  This assumes the data is refreshed on every postback.  Otherwise, write code to removed the duplicates.

    Friday, November 16, 2018 8:47 PM
  • User1281381861 posted

    Just before "Items.AddRange" you can apply "Contains" to avoid duplicates.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, November 24, 2018 2:43 PM