Binding image with DropDownList is an important concept while we are working in project. This mechanism is not achieved by simple dropdownlist. We have to add some additional jQuery to get this thing done. Here in the following link you can download the required jQuery.
Download mirrors for
JQuery.dd.js.
Create a new ASP.NET project. Add a new web form in it as I have shown in the following screenshot.
Here, I have downloaded the jQuery from above link and added to my project.
This contain some CSS files and some jQuery files.
Now in my web form I have added one ASP.NET DropDownList as follows.
- <body>
- <form id="form1" runat="server">
- <div> </div>
- <asp:DropDownList ID="DropDownList1" runat="server" Width="200px" Height="16px"> </asp:DropDownList>
- </form>
- </body>
Now here is my database table where, I get my country name.
Here is my code to bind the country and url to DropDownList.
- using System.Data;
- using System.Data.SqlClient;
- public partial class _Default: System.Web.UI.Page
- {
- SqlConnection con = new SqlConnection("Data Source=DEBENDRA;Initial Catalog=Students;User ID=sa;Password=123");
- protected void Page_Load(object sender, EventArgs e)
- {
- if(!IsPostBack)
- {
- data();
- BindTitle();
- }
- }
- public void data()
- {
- SqlDataAdapter da = new SqlDataAdapter("select * from Details", con);
- DataTable dt = new DataTable();
- da.Fill(dt);
- DropDownList1.DataSource = dt;
- DropDownList1.DataTextField = "name";
- DropDownList1.DataValueField = "url";
- DropDownList1.DataBind();
- }
- }
- Now here is my BindTitle() method.
- protected void BindTitle()
- {
- if(DropDownList1 != null)
- {
- foreach(ListItem li in DropDownList1.Items)
- {
- li.Attributes["title"] = li.Value;
- }
- }
- }
Now here I have added the jQuery and CSS in the head section in default.aspx page.
- <head runat="server">
- <title></title>
- <link href="msdropdown/dd.css" rel="stylesheet" />
- <script src="msdropdown/js/jquery-1.6.1.min.js"></script>
- <script src="msdropdown/js/jquery.dd.js"></script>
- <script type="text/javascript">
- $(document)
- .ready(function (e)
- {
- try
- {
- $("#DropDownList1")
- .msDropDown();
- }
- catch(e)
- {
- alert(e.message);
- }
- });
- </script>
- </head>
Now save and run the project you will get the following output.
So in this way you can bind Images in DropDownList.