In this article I will explain how to use the ASP.Net AJAX Rating Control in ItemTemplate ASP.Net GridView.
I will also explain how to save the Rating value of the ASP.Net AJAX the Rating Control inside GridView to Database and also populate the Average Rating value from database, saved for each Rating Control in GridView.
Using ASP.Net AJAX Rating Control inside GridView TemplateField ItemTemplate
 
Database
I am making use of two tables
1. Fruits – This table is used to populate List of Fruits in ASP.Net GridView control
Using ASP.Net AJAX Rating Control inside GridView TemplateField ItemTemplate
 
2. FruitRatings – This table is used to save the Rating Value for each fruit in the database
Using ASP.Net AJAX Rating Control inside GridView TemplateField ItemTemplate
 
 
Using the ASP.Net AJAX Control Toolkit Rating Extender Control
1. Drag an ASP.Net AJAX ToolScriptManager on the page.
2. Register the AJAX Control Toolkit Library after adding reference to your project
 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
 
Note: For more reference regarding usage of the ASP.Net AJAX Rating Control, please refer my article ASP.Net AJAX Rating Control Example
 
HTML Markup
The HTML Markup contains of an ASP.Net GridView that displays the Fruit Name and it’s rating value is displayed using an ASP.Net AJAX Control Toolkit Rating Extender Control in the GridView TemplateField ItemTemplate.
I have made use of the GridView’s DataKeys property to store the FruitId of each Fruit, it will be required while saving the aSP.Net AJAX Rating Control’s Rating Value to Database
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
<cc1:ToolkitScriptManager>
<asp:GridView ID="gvFruits" runat="server" AutoGenerateColumns="false" DataKeyNames="FruitId"
    HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2"
    AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000">
    <Columns>
        <asp:BoundField DataField="FruitName" HeaderText="Fruit Name" />
        <asp:TemplateField HeaderText="Fruit Ratings">
            <ItemTemplate>
                <cc1:Rating ID="Rating1" AutoPostBack="true" OnChanged="OnRatingChanged" runat="server"
                    StarCssClass="Star" WaitingStarCssClass="WaitingStar" EmptyStarCssClass="Star"
                    FilledStarCssClass="FilledStar" CurrentRating='<%# Eval("Rating") %>'>
                <cc1:Rating>
            <ItemTemplate>
        <asp:TemplateField>
    <Columns>
<asp:GridView>
 
 
Namespaces
You will need to import the following namespaces
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports AjaxControlToolkit
 
 
Binding the ASP.Net GridView
The GridView is populated in the Page_Load event of the ASP.Net Page using the following code. The Query written gets the FruitId, FruitName and the Average Rating of the each Fruit.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gvFruits.DataSource = GetData("SELECT FruitId, FruitName, ISNULL((SELECT AVG(Rating) FROM Fruit_Ratings WHERE FruitId = Fruits.FruitId), 0) Rating FROM Fruits");
        gvFruits.DataBind();
    }
}
 
private static DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
        return dt;
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        gvFruits.DataSource = GetData("SELECT FruitId, FruitName, ISNULL((SELECT AVG(Rating) FROM Fruit_Ratings WHERE FruitId = Fruits.FruitId), 0) Rating FROM Fruits")
        gvFruits.DataBind()
    End If
End Sub
 
Private Shared Function GetData(query As String) As DataTable
    Dim dt As New DataTable()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query)
            Using sda As New SqlDataAdapter()
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                sda.SelectCommand = cmd
                sda.Fill(dt)
            End Using
        End Using
        Return dt
    End Using
End Function
 
 
Inserting and saving the User Ratings to SQL Server Database Table
In the HTML Markup you will notice that I have set AutoPostBack property to true and also have set the OnChanged event for the Rating Extender control.
Thus when user clicks on any of the Rating Stars inside the GridView ItemTemplate, the following event is fired where the User Selected Rating is available in the RatingEventArgs Value property while the FruitId is fetched from the DataKeys property of the GridView, both are then finally inserted into database table.
C#
protected void OnRatingChanged(object sender, RatingEventArgs e)
{
    int rowIndex = ((sender as Rating).NamingContainer as GridViewRow).RowIndex;
    int fruitId = Convert.ToInt32(gvFruits.DataKeys[rowIndex].Value);
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO Fruit_Ratings VALUES(@FruitId, @Rating)"))
        {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@FruitId", fruitId);
                cmd.Parameters.AddWithValue("@Rating", e.Value);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}
 
VB.Net
Protected Sub OnRatingChanged(sender As Object, e As RatingEventArgs)
    Dim rowIndex As Integer = TryCast(TryCast(sender, Rating).NamingContainer, GridViewRow).RowIndex
    Dim fruitId As Integer = Convert.ToInt32(gvFruits.DataKeys(rowIndex).Value)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("INSERT INTO Fruit_Ratings VALUES(@FruitId, @Rating)")
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@FruitId", fruitId)
                cmd.Parameters.AddWithValue("@Rating", e.Value)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
        End Using
    End Using
    Response.Redirect(Request.Url.AbsoluteUri)
End Sub
 
 
CSS Style classes for the ASP.Net AJAX Rating Control
Below are the CSS Style Classes for the ASP.Net AJAX Rating Control, used to display the different types of stars.
<style type="text/css">
.Star
{
    background-image: url(images/Star.gif);
    height: 17px;
    width: 17px;
}
.WaitingStar
{
    background-image: url(images/WaitingStar.gif);
    height: 17px;
    width: 17px;
}
.FilledStar
{
    background-image: url(images/FilledStar.gif);
    height: 17px;
    width: 17px;
}
<style>
 
 
Demo
 
Downloads