Remove an item from DropDownList

12 Apr 20225 minutes to read

@Html.EJS().Button("first").Content("Remove 0th Item").Render()
@Html.EJS().DropDownList("games").Placeholder("Select a game").PopupHeight("200px").DataSource((IEnumerable<object>)ViewBag.data).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Text = "Game" }).Render()

<script>
    document.getElementById('first').onclick = () => {
        // create DropDownList object
        let obj = document.getElementById('games');
        if (obj.ej2_instances[0].list) {
            // Remove the selected value if 0th index selected
            var dropObject = document.getElementById("games");
            var dropDownListObject = dropObject.ej2_instances[0];
            if (dropDownListObject.index === 0) {
                dropDownListObject.value = null;
                dropDownListObject.dataBind();
            }
            // remove first item in list
            (obj.ej2_instances[0].list.querySelectorAll('li')[0]).remove();
            if (!obj.ej2_instances[0].list.querySelectorAll('li')[0]) {
                dropDownListObject.dataSource = [];
                // enable the nodata template when no data source is empty.
                obj.ej2_instances[0].list.classList.add('e-nodata');
            }
        }
        else {
            // remove first item in list
            dropDownListObject.dataSource.splice(0, 1);
        }
    };
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class GameList
    {
        public string Id { get; set; }
        public string Game { get; set; }

        public List<GameList> GameLists()
        {
            List<GameList> game = new List<GameList>();
            game.Add(new GameList { Id = "Game1", Game = "American Football" });
            game.Add(new GameList { Id = "Game2", Game = "Badminton" });
            game.Add(new GameList { Id = "Game3", Game = "Basketball" });
            game.Add(new GameList { Id = "Game3", Game = "Basketball" });
            game.Add(new GameList { Id = "Game4", Game = "Cricket" });
            game.Add(new GameList { Id = "Game5", Game = "Football" });
            game.Add(new GameList { Id = "Game6", Game = "Golf" });
            game.Add(new GameList { Id = "Game7", Game = "Hockey" });
            game.Add(new GameList { Id = "Game8", Game = "Rugby" });
            game.Add(new GameList { Id = "Game9", Game = "Snooker" });
            game.Add(new GameList { Id = "Game10", Game = "Tennis" });
            return game;
        }
    }
}