Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

JQuery Bind images to dropdownlist in asp.net

Dec 17, 2011
Introduction:

In this article I will explain how to bind images to dropdownlist in asp.net using JQuery.
Description:
  
In previous articles I explained about how to implement cascading dropdownlist  and Ajax Cascading dropdownlist. Now I will explain how to bind dropdownlist with images dynamically in asp.net using JQuery. In one of website I saw one dropdownlist that contains Country names along with country flags. I feel it’s better to write post to explain how to bind images to dropdownlist in asp.net. To implement this concept by using JQuery plugin we can achieve this easily.  
To implement concept first design table in your database and enter data as shown below

Column Name
Data Type
Allow Nulls
ID
int(set identity property=true)
No
CountryName
varchar(50)
Yes
CountryImage
varchar(50)
Yes

After completion of table creation enter data in table like as show in below.


Here I am getting images data from already inserted data if you want to dynamically insert images in database check this post insert images in folder and images path in database.

Now open Visual Studio and create new website after that right click on your website and add new folder and give name as Images and insert country flag image in that folder you should get it from attached folder.After that write the following code in your 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="msdropdown/dd.css" />
<script type="text/javascript" src="msdropdown/js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="msdropdown/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 {
$("#ddlCountry").msDropDown();
} catch (e) {
alert(e.message);
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td align="right">
<b>Country:</b>
</td>
<td>
<asp:DropDownList ID="ddlCountry" runat="server" Width="150px" onselectedindexchanged="ddlCountry_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
</td>
</tr>
<tr>
<td>
<b>Seelcted Country:</b>
</td>
<td>
<asp:Label ID="lbltext" runat="server"></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>
If you observe above code in header section I added some of script files and css file by using those files we have a chance to add images in dropdownlist. To get those files download attached sample code and use it in your application.

After completion of aspx page design add following namespaces in code behind

C#.NET Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
After add namespace write the following code


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
BindTitles();
lbltext.Text = ddlCountry.Items[0].Text;
}
}
/// <summary>
/// This Method is used to bind titles to each element of dropdown
/// </summary>
protected void BindTitles()
{
if (ddlCountry != null)
{
foreach (ListItem li in ddlCountry.Items)
{
li.Attributes["title"] = "Images/" + li.Value; // setting text value of item as tooltip
}
}
}
/// <summary>
/// Bind Dropdownlist Data
/// </summary>
protected void BindDropDownList()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true");
con.Open();
SqlCommand cmd = new SqlCommand("select * from CountryImages", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataValueField = "CountryImage";
ddlCountry.DataSource = ds;
ddlCountry.DataBind();
con.Close();
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
lbltext.Text = ddlCountry.SelectedItem.Text;
BindTitles();
}


VB.NET Code

Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls

Partial Class VbSample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindDropDownList()
BindTitles()
lbltext.Text = ddlCountry.Items(0).Text
End If
End Sub
''' <summary>
''' This Method is used to bind titles to each element of dropdown
''' </summary>
Protected Sub BindTitles()
If ddlCountry IsNot Nothing Then
For Each li As ListItem In ddlCountry.Items
' setting text value of item as tooltip
li.Attributes("title") = "Images/" & li.Value
Next
End If
End Sub

''' <summary>
''' Bind Dropdownlist Data
''' </summary>
Protected Sub BindDropDownList()
Dim con As New SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true")
con.Open()
Dim cmd As New SqlCommand("select * from CountryImages", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
ddlCountry.DataTextField = "CountryName"
ddlCountry.DataValueField = "CountryImage"
ddlCountry.DataSource = ds
ddlCountry.DataBind()
con.Close()
End Sub
Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
lbltext.Text = ddlCountry.SelectedItem.Text
BindTitles()
End Sub
End Class
If you observe above code I am binding title to dropdownlist elements by using BindTitles() method. Here our JQuery plugin will take the title of dropdownlist elements and display the images beside of the text.
  
Now run your application and check how your dropdownlist will be 

Demo


Download sample code attached


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

40 comments :

Anonymous said...

super interesting. Thanks for sharing

Anonymous said...

really nice suresh :), Im also suresh ;)

Anonymous said...

Hi Mr. Suresh ,

I use the custom dropdown v2.37.5 as the following:

1. I have a table with name COUNTRY with columns [id,countryName,flag].
2. I have a table with name MFG with columns [id,mfgName,countryID].
3.I fill the Dropdown as the following:
[Select]
[Germany]
VW
Mercedes
BMW
[Korea]
Hyundai
KIA

and so on.

What I need to do is how to make the countries items with background color?

thank you.

Anonymous said...

Very very helpful! Really saved my time of work!
Thak you very much:)
Alona (Ukraine)

Anonymous said...

hi this is deepak garg,
i have gone through many blogs but your blog has really some different tutorials.
now i have decided to read your blog regularly.
pls if u can then also start tutorial which tell how exactly a project should be started with proper SDLC process. that will really help me .......
this is my email id deepagargak@gmail.com
thanks

Anonymous said...

After running this code on re sizing an image after upload and still retaining the same quality, i got this error.

error 'System.Web.UI.WebControls.Image' does not contain a definition for 'FromStream'
Validation Complete

Anonymous said...

After running this code on resizing an image after upload i got this error.

error 'System.Web.UI.WebControls.Image' does not contain a definition for 'FromStream'
Validation Complete

Bright Future said...

Hi!
really nice article but i am facing problem when using update panel Is there any solution?

Anonymous said...

there is no single line of code to bind images.it is not at all working. it is a wrong post.

Suresh Dasari said...

@ Comment 9...
Before give wrong comment check the code i am binding images in code behind. Check it once if it not works means how can i show the demo. Please check thoroughly before give wrong comments...

Anonymous said...

man you r d best............

Anonymous said...

thnk u...

Anonymous said...

Does it work with Masterpages?

Suresh Dasari said...

yeah it will work in masterpages also...

Vineeth Kumar said...

Hi suresh iam using a increment of rows in the html page using javascript with row elements(checkbox,dropdownlist,textarea)in each row
the problem is how can i bind data from sql server so that dropdownlist of each row should fetch data from database...

chandana said...

awesome. i need a code to implement the SQL database data with multiple sheets in same excel sheet in c# .net. will you help me

raj yadav said...

after executing it shows the msg that "" $("#ddl_Operator").msDropDown() "" is not a function

raj yadav said...

plzz help me to solve this problem !!!!

Anonymous said...

is there a way to set value for the dropdown box?

Anonymous said...

"after executing it shows the msg that "" $("#ddl_Operator").msDropDown() "" is not a function"

"#ddl_Operator" y0u should replace it with the dropdown ID, i guess that helps

KISLAY RATHORE said...

after executing it shows the msg that "" $("#ddl_Operator").msDropDown() "" is not a function

KISLAY RATHORE said...

help me sir

Yunus Pathan said...

country change page refresh.
i use dropdown list
in asp update panel flag image not retrive....
any suggestion how to stop page reload.....

Anonymous said...

absolutely working great work thank you..

Anonymous said...

Hey When I Created a Insert Option For This Dropdown and allowed user to insert some images with names in to The dropdown the dropdown certainly braking in to two after inserting. and when i refresh then again it is coming in to one is their any solution for this problem.

Khumesh Kumawat said...

Its very userful & interesting article!!

Anonymous said...

your code is awesome. It worked for me.
Now i want to remove scroll from dropdown.
Please help me out.. Thanks in advance

Anonymous said...

This code not work in IE browser. is ther any solution for it. Please help me out. Thanks in advance.

Anonymous said...

Is is possible to apply this code for more than 2 dropdown??

Rahul said...

Hi Suresh,

This code works perfectly.

How do I change the image size?

I have some images which are large and some are small. So it makes my ddl look clumpsy and bad.

Thanks in advance

Anonymous said...

where to find javascript files ?

Rahul Mishra said...

this is not work with Masterpages

Diviya Vinolin Add said...

i want comments coding

Bhrugesh Thakkar said...

Hello Suresh...U r doing great...m regularly visiting ur site and m fan of you...

but here when I m using this code in content page..its not work at all...

I am using master pages and update panel in content page...update panel has asynchronous trigger on save button
so can you please tell me how to use same code in master page...
thnx in advance

Anonymous said...

DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "CountryName";
DropDownList1.DataValueField = "CountryImage";
DropDownList1.DataBind();
con.Close();
foreach (ListItem ListItem in DropDownList1.Items)
{
ListItem.Attributes["title"] = "CountryImages/" + ListItem.Value;
}

hi suresh,
i am using no sql database(couchdb).i have list of item name and list of image path.so whenever i am giving imagepath in DropDownList1.DataValueField , it gives error.please help me,my mail id is shekharchauhan91@gmail.com

shekhar chauhan said...

$(document).ready(function (e) {
try {
$("#MainContent_FormItem_3_3").msDropdown();
} catch (e) {
alert(e.message);
}
});


when i am using above code.this gives alert 'undefined is not a function'.
that is why i am not able to bind image in dropdownlist control.
please help.

shekhar chauhan said...

$(document).ready(function (e) {
try {
$("#MainContent_FormItem_3_3").msDropdown();
} catch (e) {
alert(e.message);
}
});

this jquery is giving alert message in mozila:
'$(...).msDropdown is not a function'

Aron Carter xD said...

Can this work inside GridView?
I have put DropdownList in GridView control, but its not working correctly

Here's the code to find ID

$(document).ready(function (e) {
$('#<%=GridProcessFlow.ClientID %>').find('span[id$="ddlLegends"]').msDropDown();
});

Its finding the control, filling the name but not images. i guess it's not able to apply CSS.

Divyesh Jain said...

not working sir

Prashant said...

Hi suresh
its working absolutely fine but i can't get the value of drop down and i cant set the particular value in drop down is there any solution then please help me

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.