Introduction
This article explains how to bind images with text in a dropdownlist from your table.
Requirement
- A table as in the following.
Table design:
Table data:
Code.aspx
I have used a DropdownList control to bind data from the table "ddl_image". Before doing the design you need the files "ddl.css", "jquery-1.6.1.min.js" and "jquery.dd.js". You can download them from here.
Add the following code in the aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Dropdownlist with Images</title>
<link rel="stylesheet" type="text/css" href="dropdown/ddl.css" />
<script type="text/javascript" src="dropdown/js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="dropdown/js/jquery.dd.js"></script>
<!-- Script is used to call the jQuery for dropdown -->
<script type="text/javascript" language="javascript">
$(document).ready(function (e) {
try {
$("#ddlprofile").msDropDown();
} catch (e) {
alert(e.message);
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td align="right">
<b>Profile:</b>
</td>
<td>
<asp:DropDownList ID="ddlprofile" runat="server" Width="150px" onselectedindexchanged="ddlCountry_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
</td>
</tr>
</table>
</form>
</body>
</html>
Code.cs
Here I tried to addd a dropdownlist first, then bind the titles and then call both functions on pageload as in the following.
1. Bind dropdownlist
protected void Bindddl()
{
SqlConnection con = new SqlConnection("Data Source=nehashama;Initial Catalog=rp;Integrated Security=true");
con.Open();
SqlCommand cmd = new SqlCommand("select * from ddl_image", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
ddlprofile.DataTextField = "Name";
ddlprofile.DataValueField = "Profile_image";
ddlprofile.DataSource = ds;
ddlprofile.DataBind();
con.Close();
}
2. Bind Title
protected void BindTitle()
{
if (ddlprofile != null)
{
foreach (ListItem li in ddlprofile.Items)
{
li.Attributes["title"] = "ddl/" + li.Value; // it ll set the value of items in dropdownlist as tooltip
}
}
}
3. Call on Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindddl();
BindTitle();
}
}
Now save all and view the page in a browser, it will work fine and will look as in the following image: