Add item in between in DropDownList

7 Jun 20244 minutes to read

You can add item in between based on item index. If you add new item without item index, item will be added as last item in list.

<div class="control-wrapper">
    <div id="default" style='padding-top:75px;'>
        <ejs-dropdownlist id="games" dataSource="@ViewBag.data" placeholder="Select a game" index="2" popupHeight="220px">
            <e-dropdownlist-fields value="Game"></e-dropdownlist-fields>
        </ejs-dropdownlist>
    </div>
</div>
<div>
    <ejs-button id="first" content="add item (Hockey) in first"></ejs-button>
</div>
<div>
    <ejs-button id="between" content="add item (Golf) in between"></ejs-button>
</div>
<div>
    <ejs-button id="last" content="add item (Cricket) in last"></ejs-button>
</div>
<script>
    document.getElementById('first').onclick = () => {
        var dropObject = document.getElementById("games").ej2_instances[0];
        dropObject.addItem({Game: 'Hockey' }, 0);
    };
    // add item in between
    document.getElementById('between').onclick = () => {
        var dropObject = document.getElementById("games").ej2_instances[0];
        dropObject.addItem({ Game: "Golf" }, 2);
    };
    // add item at last
    document.getElementById('last').onclick = () => {
        var dropObject = document.getElementById("games").ej2_instances[0];
        dropObject.addItem({Game: "Cricket"});
    };
</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;
        }
    }
}