Pages

Thursday 28 August 2014

How to use Select2 jquery with Asp.net controls

A brief description to create auto complete dropdownlist or multiselect listbox.


First we will see how to use a dropdown with select2 jquery.

look at the below picture. we have to create a dropdown with select2 jquery.

To create dropdown with select2, first create a dropdown in aspx page like below


<form id="form1" runat="server">
        <div>
            <asp:DropDownList  ID="lstJobs" runat="server" Width="300px" ></asp:DropDownList>
        </div>
    </form>

Now in .cs page you can bind this dropdown 

protected void Page_Load(object sender, EventArgs e)
    {
        loadJobs();
    }
    private void loadJobs()
    {
        DataSet ds = new DataSet();
    // you can bind your data with xml file or you can fetch data from database to BLL to your              //dataset ds.
        ds.ReadXml(Server.MapPath("~/xml/export.xml"));
        lstJobs.DataSource = ds.Tables[0];
        lstJobs.DataTextField = "Text";
        lstJobs.DataValueField = "ID";
        lstJobs.DataBind();

    }

Now go to aspx page and add select2 jquery and other jqueries as below mentioned.

<head runat="server">
    <title></title>
    <script src="JS/jquery-1.7.1.js"></script>
    <script src="JS/jquery-1.7.1.min.js"></script>
    <script src="JS/select2.js"></script>
    <link href="JS/select2.css" rel="stylesheet" />
    <script>
        $(document).ready(function () {
            $("#" + "<%=lstJobs.ClientID%>").select2({
                placeholder: "Select a Subject",
                allowClear: true
            });
        });
    </script>
</head>

Note: Remember, you add this jquery link to <head> section of your page.

now run this, you will get your desired output.

Hope you are enjoying.







3 comments:

  1. The Wynn casino opens - KTM Hub
    “Wynn's Casino and Resort is 여주 출장안마 opening today.” 구미 출장안마 This is 사천 출장마사지 a 김천 출장안마 direct response to the recent COVID-19 세종특별자치 출장안마 pandemic. The Wynn

    ReplyDelete