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

Ajax rating control example with database or how to display value from database in rating control or display average rating for article using asp.net

May 9, 2011
Introduction:

Here I will explain how to use Ajax rating control with database to display average rating for particular article using asp.net

Description:

Previously I explained
how to use Ajax Collapsible panel . Now I will explain how to use Ajax rating control with Database in asp.net. In many sites we will see rating options for books, articles and movies etc by giving rating option to user we have chance to know about particular thing how much users are feeling comfort with particular thing. In Ajax we have a rating control by using that we can display the rating option easily. Here I am storing each user rating details into database and displaying the average rating based on number of users rating. To achieve this first design one table in your database and give name like RatingDetails if you want to give another name you can but you need to change table name in code also.

Column Name
Data Type
Allow Nulls
Id
Int(Set Identity=true)
No
Rate
int
Yes
After completion of design table in database add AjaxControlToolkit reference to your application after that add
<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" tagPrefix="ajax" %>

To your aspx page and design your page likes this

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Rating Sample</title>
<style type="text/css">
.ratingEmpty
{
background-image: url(ratingStarEmpty.gif);
width:18px;
height:18px;
}
.ratingFilled
{
background-image: url(ratingStarFilled.gif);
width:18px;
height:18px;
}
.ratingSaved
{
 background-image: url(ratingStarSaved.gif);
width:18px;
height:18px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScripManager1" runat="server"/>
<div>
<asp:UpdatePanel ID="pnlRating" runat="server">
<ContentTemplate>
<table width="35%">
<tr>
<td width="27%">
<b>Average Rating:</b>
</td>
<td>
<ajax:Rating ID="ratingControl" AutoPostBack="true" OnChanged="RatingControlChanged" runat="server" StarCssClass="ratingEmpty" WaitingStarCssClass="ratingSaved" EmptyStarCssClass="ratingEmpty" FilledStarCssClass="ratingFilled">
</ajax:Rating>
<b> <asp:label ID="lbltxt" runat="server"/> </b>
</td>
</tr>
<tr>
<td colspan="2">
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
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
If you observe above code I define lot of properties to ajax:Rating now I will explain all the properties of Ajax rating control

AutoPostBack – This property should be true because we are storing rating details during rating item click.

OnChanged – This event is used to get how many stars user has selected.

StarCssClass – This cssclass is used for to display starts.

WaitingStarCssClass – This cssclass is used to show the starts color during saving the rating value.

EmptyStarCssClass – This cssclass is used to display empty starts color.

 FilledStarCssClass – This cssclass is used to display filled stars color.
 CurrentRating – This property is used to display Initial rating value (Number of starts to be filled initially).

MaxRating – This property is used to display maximum rating value (No. of starts here I am displaying only 5 if you want to increase starts value give property like this MaxRating=10).

ReadOnly – This property is used to make rating control read only.

RatingAlign – This property is used to set starts vertical or horizontal.

RatingDirection – This property is used to set the direction of stars(LeftToRight or TopToBottom or RightToLeft or BottomToTop).

Now in code behind add following namespaces

C# Code

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After completion of adding namespaces in code behind add following code


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindRatingControl();
}
}
protected void RatingControlChanged(object sender, AjaxControlToolkit.RatingEventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RatingDetails(Rate)values(@Rating)",con);
cmd.Parameters.AddWithValue("@Rating", ratingControl.CurrentRating);
cmd.ExecuteNonQuery();
con.Close();
BindRatingControl();
}
protected void BindRatingControl()
{
int total = 0;

DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("Select Rate from RatingDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt.Rows.Count>0)
{
for(int i=0;i<dt.Rows.Count;i++)
{
total += Convert.ToInt32(dt.Rows[i][0].ToString());
}
int average = total/(dt.Rows.Count);
ratingControl.CurrentRating = average;
lbltxt.Text = dt.Rows.Count+"user(s) have rated this article";
}
}
VB Code

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient

Partial Class _Default
Inherits System.Web.UI.Page
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindRatingControl()
End If
End Sub
Protected Sub RatingControlChanged(ByVal sender As Object, ByVal e As AjaxControlToolkit.RatingEventArgs)
con.Open()
Dim cmd As New SqlCommand("insert into RatingDetails(Rate)values(@Rating)", con)
cmd.Parameters.AddWithValue("@Rating", ratingControl.CurrentRating)
cmd.ExecuteNonQuery()
con.Close()
BindRatingControl()
End Sub
Protected Sub BindRatingControl()
Dim total As Integer = 0
Dim dt As New DataTable()
con.Open()
Dim cmd As New SqlCommand("Select Rate from RatingDetails", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
total += Convert.ToInt32(dt.Rows(i)(0).ToString())
Next
Dim average As Integer = total \ (dt.Rows.Count)
ratingControl.CurrentRating = average
lbltxt.Text = dt.Rows.Count & "user(s) have rated this article"
End If
End Sub
End Class
Now in web.config file set your database connection because in above code I am getting connection from web.config

<connectionStrings>
<add name="dbConnection" connectionString="Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true"/>
</connectionStrings>
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

47 comments :

jia said...

hi..
This article was very helpful to me...But how to display the rating stars in decimal..plz could u send me the code...

Anonymous said...

Hi,
this article was very helpful but this rating control is shown how many user's rate this article .... I have different scenario let suppose we have 20 pages in our website each page have rating control so how we managed this not user wise but pages wise each page have different id and posts in website have different id...

Please help me to solve this ...

Thanks advance for this

Anonymous said...

How to make star visible ?????????

Kerron said...

Hi Suresh,

This is exactly what I am looking for, but I am not versed in C#. Can you rework the code for use with a VB project?

Thanks,
Kerron (defkerron@yahoo.com)

Suresh Dasari said...

@Kerron,
i added VB code also please check the post.

Kerron said...

thanks bro, much appreciated

Anonymous said...

i like this site.this was very useful.keep going

Jm said...

I appreciate the VB code. Just what I needed. thanks.

Anonymous said...

Great example; I was wondering how would you program the VB code behind if there was a 3rd data colum "ContentId"(int) to sort the average rating by contentID... I really stuck any ideas?

Thanks, Jm

Anonymous said...

Hello! I get this messages. Please let me know how to fix it.
Thank you

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Anonymous said...

Hi! Thank you for your job! All working. But i can't add a few ratings on the same page. How to do that? Please help.
Regards
Max

Jitendra Kumar Prajapati said...

Its too much good Article..........

Unknown said...

nice post

Suresh Dasari said...

@Comment 10
that error because of your sql connection failure check this post to solve that problem
http://www.aspdotnet-suresh.com/2011/11/network-related-or-instance-specific.html

srinivas said...

hi suresh nice post but stars are not visible for why please tell me

Anonymous said...

this is good,but without using database how i can implement this

Anonymous said...

very good article,honey chawla

Thép hình said...

Error: Could not load type 'System.Web.UI.ScriptReferenceBase' from assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
I use ASP.net V3.5

rajasekhar said...

it's good

rajasekhar said...

please send me AJAX PPTS

rajasekhar said...

stars in not visiable during runing time why tell me

John said...

Thanks so much for all you write. Do you have an example of how to insert ratings into database from gridview and get average?

Rahul said...

awesome article man.Thanx a lot

Unknown said...

Gud One Sir :-) :)

Pratibha said...

How to use onclientcallback with Ajax Rating control?

Unknown said...

Hi Suresh very nice article...i need to change the rating when it is kept inside datalist...suggestions plz.....

Anonymous said...

suresh sir im use
protected void rating()
{

int total = 0;

DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("Select Rate from Rating_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
total += Convert.ToInt32(dt.Rows[i][0].ToString());
}
int average = total / (dt.Rows.Count);
ratingControl.CurrentRating = average;
lbltxt.Text = dt.Rows.Count + "user(s) have rated this article";
}
this method but when i debug code breakpoint not going in if condition after da.Fill(dt); it out

Anonymous said...

suresh sir im use
protected void rating()
{

int total = 0;

DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("Select Rate from Rating_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
total += Convert.ToInt32(dt.Rows[i][0].ToString());
}
int average = total / (dt.Rows.Count);
ratingControl.CurrentRating = average;
lbltxt.Text = dt.Rows.Count + "user(s) have rated this article";
}
this method but when i debug code breakpoint not going in if condition after da.Fill(dt); it out

iam using asp.net 2.0 with ajaxcontrol 1.0

Anonymous said...

hi suresh

it is good .. very good

Anonymous said...

sadfasdfasdf

Unknown said...

hai suresh can u explain how to give rating using button click

Anonymous said...

i am using same thing in Datalist but it's now working , ther is any other way to use it in the datalist ..!!!

prasad said...

hi suresh sir,,,
how we use data list control in three tier,how we declare the datalist in .cs page and dal,bal .

Santosh Vighne said...

its very amazing code and very useful,
Thanks sir

Anonymous said...

Suresh Sir i m not able to see the stars at run time, and i knw only c# i dont knw vb so can u help me

Anonymous said...

Use this code in ur website... U 'll be having only 5 starts as the average...

Anonymous said...

Hi Suresh,

Really a good one....i used this code working prefect but am in need of all three star images ll you pls send me images to muralitharan.ba@neeyamo.com coz here i cant download the source

azad chouhan said...

hey suresh please tell me once i vote anybody 5 star then next time i can not able to give five star again. I tried it on another browser also but i can give 4,3,2,1 star but not 5 star anymore until anybody give less then 5 what is the reason please explain me
thanks
azad chouhan

Unknown said...

It is very useful.

Anonymous said...

Suresh Sir i m not able to see the stars at run time.

Manish said...

Thanks Suresh so far everything is working fine. Can you please guide how this can be used for Half Star OR Quarter Star Ratings. Appreciate

Unknown said...

sir i am using ajax rating control but i am facing a issue plz help me ..my issue is ..when i give rating first time then it work fine when again give same rating it does not fire.
for ex when.i give 3 rating if i again gives 3 rates, onchaged event is not fired..sir plz help ..

lyricist said...

sir ,

how can i use this rating control inside datalist ..?

please give reply urgent ..
thanking you sir..

Anonymous said...

hi sir
i have run your sample code but i have one error ,the error is
protected void BindRatingControl()
{
int total = 0;

DataTable dt = new DataTable();
con.Open(); ->(eror in this place)
SqlCommand cmd = new SqlCommand("Select Rate from RatingDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt.Rows.Count>0)
{
for(int i=0;i<dt.Rows.Count;i++)
{
total += Convert.ToInt32(dt.Rows[i][0].ToString());
}
int average = total/(dt.Rows.Count);
ratingControl.CurrentRating = average;
lbltxt.Text = dt.Rows.Count+"user(s) have rated this article";
}
}
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

how to retify these error,pls help me

Rajaram Elumalai said...

suresh it is very useful for me ,i loke u r all thoues metiralis thanks suresh

Ravi said...

Superb and Usefull article.
Thanxs

Unknown said...

I think there is logical error in this line
cmd.Parameters.AddWithValue("@Rating", ratingControl.CurrentRating);
user e.Value to get the ratings from user.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 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.