Add select2 to new DropDownList [C#][asp.net]

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”;
selection_model.Controls.Add(dropDownList);
}
Now I need to connect this object to the select2() script. But i don’t know how.
How can i do this?
Thanks

Select2 only works on HTML <select> elements in the web page’s Document Object Model (DOM). Does your C#/ASP.net code create a <select> element? If so, you should also be able to arrange for your C#/ASP.net 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 ">
</asp:DropDownList>

script>
$(document).ready(function () { $("#ddl1").select2(); });
</script

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:

thanks

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 ASP.net 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.

10

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 */});
    });
</script>
1 Like

Really thanks. That was the solution at my problem!