Add select2 to new DropDownList [C#][]


Hi guys i’m trying to create a new dropdownlist that is created by a click of a button.
The creation of a new Dropdown list is simple:
protected void Btn_Add_Team_Selection(object sender, EventArgs e)
DropDownList dropDownList = new DropDownList();
dropDownList.ID = “ddl_1”;
Now I need to connect this object to the select2() script. But i don’t know how.
How can i do this?


Select2 only works on HTML <select> elements in the web page’s Document Object Model (DOM). Does your C#/ code create a <select> element? If so, you should also be able to arrange for your C#/ code to output the necessary JavaScript code to initialize your <select> element with the Select2 widget.


In a static Pages i’m using this:
<asp:DropDownList ID=“ddl1” runat=“server” CssClass=“form-control” ToolTip="Select ">

$(document).ready(function () { $("#ddl1").select2(); });

but when i try to load the same things by c# dinamically the select2 script doesn’t work.

However now i will try with the object.
But if someone know how to use the dropdownlist is better for me :slight_smile:



Can you paste here the HTML output of your C# code? I’m not familiar with C#, so I’m not sure what the output of your code would look like. If it is similar to the code you showed above, then it should work the same. I will be able to tell better off I can see the HTML output of the C# code.


Sure this is the output, you are right the code generated is with the tag.

So which is the script to apply and use?

Thanks :slight_smile:


So it looks like you just need some JavaScript at the end of your <body> element to initialize the #ddl_Select_Team <select> with the Select2 widget. With jQuery, it would look something like this (assuming you’ve already loaded jQuery and Select2 in the <head> portion of your page):

<script type="text/javascript">
    $(function() {
        $('#ddl_Select_Team').select2({/* options, if  you want them */});


Really thanks. That was the solution at my problem!