Reputation: 29
SqlConnection myDBCon = new SqlConnection(sc);
SqlCommand command = new SqlCommand("select Caption_name from Commercial_caption", myDBCon);
myDBCon.Open();
SqlDataAdapter mySqlAdapter = new SqlDataAdapter();
mySqlAdapter.SelectCommand = command;
DataSet ds = new DataSet();
mySqlAdapter.Fill(ds);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataTextField = "Caption_name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--SELECT--","0"));
myDBCon.Close();
Upvotes: 1
Views: 23353
Reputation: 2542
You can use Select2
The jQuery replacement for select boxes
. First include these files and you can download them from Here
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/select2.js"></script>
<link href="css/select2.css" rel="stylesheet" />
ASP
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="custom" AutoPostBack="true">
</asp:DropDownList>
Java Script
<script type="text/javascript">
$(document).ready(function () {
$("#DropDownList1").select2({
placeholder: "Select an option",
allowClear: true
});
});
</script>
Custom CSS for increasing the width of DropDownList
<style type="text/css">
.custom
{
width: 50%;
}
</style>
Your code behind logic remains the same. I have tested it and its working fine.
Code Behind
SqlConnection myDBCon = new SqlConnection(sc);
SqlCommand command = new SqlCommand("select Caption_name from Commercial_caption", myDBCon);
myDBCon.Open();
SqlDataAdapter mySqlAdapter = new SqlDataAdapter();
mySqlAdapter.SelectCommand = command;
DataSet ds = new DataSet();
mySqlAdapter.Fill(ds);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataTextField = "Caption_name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("",""));
myDBCon.Close();
Note: You need to add an empty item at 0th index and select2
have option for placeholder.
Upvotes: 4