Tuesday 31 July 2012

SHOW COUNTER ON WEBSITE


STEP1
create a table Counter(CounterID bigint primary key identity,CounterName bigint,Updatedon datetime)
and insert a value
insert into Counter values(0,1);

STEP2
now create a procedure as

CREATE proc Counter_acteon
as
Declare @counter bigint
set @counter=(select top(1) CounterNumber from counter order by updatedon desc)
set @counter=@counter+1
insert Counter (counternumber) values (@counter)
SELECT RIGHT(replicate('0',7)+convert(varchar,@counter),8) as counter

STEP3

and open website where you want to add a counter
add a label control as

<asp:Label ID="lbl_counter" runat="server" ForeColor="White" 
                                    BackColor="Black" Font-Bold="True" Font-Size="Large" BorderStyle="Ridge"></asp:Label>

STEP4
write code on page load

public partial class _Default : System.Web.UI.Page
{

    cscounter csd = new cscounter();
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt =csd.setcounter();
        lbl_counter.Text = dt.Rows[0][0].ToString();
    }
}

STEP5
then add a Class File and code following
public class cscounter
{
    public cscounter()
    {
    
    }

    private int _counter;


public int Counter
{
  get { return _counter; }
  set { _counter = value; }
}

public DataTable  setcounter()
{
    SqlConnection con = new SqlConnection("Data Source=SERVER2008R2\\ONLINE24X7; User ID=sa; Password=stream@1234; Initial Catalog=BSAWEBSITE;");
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "sp_select";
    cmd.CommandType = CommandType.StoredProcedure;

    DataTable dt = new DataTable();
    cmd.Connection = con;
    con.Open();
    SqlDataAdapter datadp = new SqlDataAdapter(cmd);
    datadp.Fill(dt);
  
    return dt;
}
}

Monday 30 July 2012

UPLOAD AN IMAGE AND SHOW ALERT BOX if not chosen any file(upload from  in admin folder and upload image folder out of admin form)


protected void btnsubmit_Click(object sender, EventArgs e)
        {
            string filename = fileupload1.FileName;
            //string path = Server.MapPath("")+"/"+"images"+"/"+filename;

            if (txttitle.Text == null && (!fileupload1.HasFile))
            {
                string bpath = Server.MapPath("//" + "images" + "//" + filename);
                fileupload1.SaveAs(bpath);
                string imgpath = "~" + "/" + "images" + "/" + filename;
                db.Imagetitle = txttitle.Text;
                db.Imagepath = imgpath;
                db.Enteredby1 = 1;
                db.image_insert();
                txttitle.Text = null;
                ScriptManager.RegisterClientScriptBlock(btnsubmit, this.GetType(), "Salik", "alert('Image upload Successfully');", true);
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(btnsubmit, this.GetType(), "Salik", "alert(' You have not selected any file or title');", true);
            }

        }

<body>
    <form id="form1" runat="server">
    <div>
    <br />
    <center>
    <fieldset style="width:420px; height:200px">
    <legend>Upload Image</legend>
    <table style="height: 160px; width: 377px">
    <tr>
    <td colspan="2"></td>
    </tr>
    <tr>
    <td class="style1">Title</td>
    <td><asp:TextBox ID="txttitle" runat="server" Width="150px" Height="22px"></asp:TextBox></td>
    </tr>
    <tr>
    <td class="style1">Upload Image</td>
    <td>
    <asp:FileUpload ID="fileupload1" runat="server" />
    </td>
    </tr>
    <tr>
    <td class="style1"></td>
    <td>
    <asp:Button ID="btnsubmit" runat="server" Text="Submit" onclick="btnsubmit_Click" />
    </td>
    </tr>
    </table>
    </fieldset>
    </center>
    </div>
    </form>
</body>

Open a Javascript  popup on Click a Gridview Show Button

 protected void Grid_reg_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    int id = Convert.ToInt32(Grid_reg.DataKeys[e.Row.RowIndex].Values["RegistrationID"]);
                    Session["regisid"] = id.ToString();
                    Button lbtnfname = e.Row.FindControl("btnshow1") as Button;

                    lbtnfname.OnClientClick = "window.open('Admin_regshow.aspx?id=" + id + "','','toolbar=0,scrollbars=1,width=700');return false;";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
//Add a new web page and design following
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
    .td1
    {
        width:150px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <center>
    <asp:FormView ID="Formview1" runat="server" Width="75%" >

 <ItemTemplate>
 <table class="tbl" >
  <tr>
  <td class="td1">RegistrationID</td>
  <td><%# Eval("RegistrationID")%></td>
  </tr>
 
  <tr>
  <td>Title </td>
  <td> <%# Eval("Title")%>
  </td>
  </tr>
  <tr>
  <td> Name</td>
  <td><%# Eval("Name")%></td>
  </tr>
    <tr>
  <td>PhoneNo</td>
  <td><%# Eval("PhoneNo")%></td>
  </tr>
  
   <tr>
  <td>EmailID</td>
  <td><%# Eval("EmailID")%></td>
  </tr>
   <tr>
//write on codebehind file
public partial class admin_registr : System.Web.UI.Page
    {
         string apid;
         C_Application db = new C_Application();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["id"] != null)
                {
                    apid = Request.QueryString["id"];
                   
                }

                else
                {
                    Response.Redirect("~/Login.aspx");
                }

                show1();
            }
        }

        public void show1()
        {
            DataSet ds = new DataSet();
            ds = db.Datalist1_bind(Convert.ToInt32(apid));
            Formview1.DataSource = ds;
            Formview1.DataBind();
          
        }
      
    }

Friday 27 July 2012

INSERT MULTIPLE ROWS  IN DATABASE FROM A GRID VIEW 

protected void btnsave_Click(object sender, EventArgs e)
        {
     
            for (int i = 0; i < Grid_fee.Rows.Count; i++)
            {
                TextBox amount = (TextBox)Grid_fee.Rows[i].Cells[1].FindControl("txt_amount");
                Label semeid = (Label)Grid_fee.Rows[i].Cells[1].FindControl("lbl_semeid");

                cm.amount = amount.Text;
                cm.memberid = Convert.ToInt64(Session["MemberID"].ToString());
             
                cm.semesterid=Convert.ToInt64(semeid.Text);
                cm.enteredby = Convert.ToInt64(Session["UserID"]);
                cm.feessave();
              
            }
          
        }

class file
namespace AccessLayer
{
    public class CommonMaster
    {
        public System.Int64 memberid
        {
            get;
            set;
        }
        public System.Int64 semesterid
        {
            get;
            set;
        }
        public System.String amount
        {
            get;
            set;
        }
      
        public System.Int64 enteredby
        {
            get;
            set;
        }
      public DataSet feessave()
        {
            SqlCommand cmdfees = new SqlCommand();
             cmdfees.CommandType = CommandType.StoredProcedure;
            cmdfees.CommandText = "studentfee_insert";
            cmdfees.Parameters.AddWithValue("@memberid", memberid);
            cmdfees.Parameters.AddWithValue("@semesterid", semesterid);
            cmdfees.Parameters.AddWithValue("@amount", amount);
            cmdfees.Parameters.AddWithValue("@enteredby", enteredby);
            con.open();
            cmd.executeNonQuery();
             
        }

Thursday 19 July 2012

Find Second and Third Height Salary in SQL Server

 --Find second height salary--

select MAX(salary) from emp2 where salary<(select MAX (salary ) from emp2)
--or
select max(salary) from emp where salary  not in (select distinct top 1  salary from emp order by salary desc )
--or
select min(salary) from emp where salary  in (select distinct top 2  salary from emp order by salary desc )

--find third height salary--
select max(salary) from emp where salary  not in (select distinct top 2  salary from emp order by salary desc )
--or
select min(salary) from emp where salary  in (select distinct top 3  salary from emp order by salary desc )

--find all details of emp where emp  salary have been second height--

select *from emp where salary in(select MAX(salary) from emp where salary not in(select distinct top 1 salary from emp order by salary desc))
--or
select *from emp where salary in(select MIN(salary) from emp where salary  in(select distinct top 2 salary from emp order by salary desc))

--Find all details of emp where emp salary is third height--

select *from emp where salary in(select MAX(salary) from emp where salary not in(select distinct top 2 salary from emp order by salary desc))
--or
select *from emp where salary in(select MIN(salary) from emp where salary  in(select distinct top 3 salary from emp order by salary desc))

Saturday 14 July 2012

Sending mail with multiple file attachments using gmail in Asp.Net

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Send mail with multiple file attachments using Gmail in Asp.Net</title>
    <script type="text/javascript">
        function addTypeFile() {
            if (!document.getElementById || !document.createElement)
                return false;

            var uploadArea = document.getElementById("upload-area");

            if (!uploadArea)
                return;

            var newLine = document.createElement("br");
            uploadArea.appendChild(newLine);

            var newTypeFile = document.createElement("input");
            newTypeFile.type = "file";
            newTypeFile.size = "60";

            if (!addTypeFile.lastAssignedId)
                addTypeFile.lastAssignedId = 100;

            newTypeFile.setAttribute("id", "file1" + addTypeFile.lastAssignedId);
            newTypeFile.setAttribute("name", "file1:" + addTypeFile.lastAssignedId);
            uploadArea.appendChild(newTypeFile);
            addTypeFile.lastAssignedId++;
        }
</script>

</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<p>To:</p>
<p>
<asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
</p>
<p>Subject:</p>
<p>
<asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
</p>
<p>Message Body:</p>
<p>
<asp:TextBox ID="txtMsgBody" runat="server" TextMode="MultiLine" Columns="80" Rows="10"></asp:TextBox>
</p>
<p>
Attachment:
</p>
<p id="upload-area">
   <input id="File1" type="file" runat="server" size="60" />
</p>
<p>
<a href="#" onclick="addTypeFile()">Attach another file</a>
</p>
<p><asp:Button ID="btnSubmit" runat="server" Text="Send" OnClick="btnSubmit_Click" /></p>
<span id="Span1" runat="server" />
</form>
</body>
</html>

aspx.cs code

using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

public partial class Mailsending2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
         try
        {
            List<Attachment> attachment = new List<Attachment>();
            HttpFileCollection uploads = HttpContext.Current.Request.Files;
            for (int i = 0; i < uploads.Count; i++)
            {

                if (uploads[i].FileName.Length == 0)
                    continue;
                attachment.Add(new Attachment(uploads[i].InputStream, uploads[i].FileName));
            }
            MailSender.SendMail(txtTo.Text, txtSubject.Text, txtMsgBody.Text, attachment);
            Span1.InnerHtml = "Mail send successfully." ;
        }
        catch (Exception ex)
        {
            Span1.InnerHtml = ex.Message;
        }
    }
    }

Class File

using System.Web;
using System.Net;
using System.Net.Mail;

/// <summary>
/// Summary description for MailSender
/// </summary>
public class MailSender
{
    public MailSender()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static bool SendMail(String to, String subject, String messageBody, List<Attachment> attachmentCollection)
    {
        try
        {
            NetworkCredential networkCredential = new NetworkCredential("usermailid@gmail.com", "password");
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(networkCredential.UserName);
            mailMessage.To.Add(new MailAddress(to));
            mailMessage.Subject = subject;
            mailMessage.Body = messageBody;
            mailMessage.IsBodyHtml = true;

            foreach (Attachment attachment in attachmentCollection)
            {
                mailMessage.Attachments.Add(attachment);
            }

            mailMessage.Priority = MailPriority.High;
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = networkCredential;
            smtpClient.Send(mailMessage);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}

Sending email in asp.net using smtp gmail server

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            color: #660066;
        }
        .style2
        {
            color: #0000CC;
        }
        .style3
        {
            color: #336699;
        }
        .style4
        {
            color: #666699;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div><center>
    <table style="height: 257px; width: 536px">
    <tr>
    <td class="style1"><strong>To</strong></td><td><asp:TextBox ID="txtto" runat="server" Height="25px" Width="360px"></asp:TextBox></td>
    </tr>
    <tr>
    <td class="style2"><strong>From</strong></td><td><asp:TextBox ID="txtfrom" runat="server" Height="25px" Width="360px"></asp:TextBox></td>
    </tr>
    <tr>
    <td class="style3">Subject</td><td><asp:TextBox ID="txtsubject" runat="server" Height="25px" Width="360px"></asp:TextBox></td>
    </tr>
    <tr>
    <td class="style4">Message</td><td><asp:TextBox ID="txtmessage" runat="server"
            TextMode="MultiLine" Height="90px" Width="367px"></asp:TextBox></td>
    </tr>
    <tr>
    <td></td><td><asp:Button ID="btnsave" runat="server" Text="submit"
            onclick="btnsave_Click" /></td>
    </tr>
    </table></center>
    </div>
    </form>
</body>
</html>
aspx.cs Code  
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

public partial class Emailsending : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnsave_Click(object sender, EventArgs e)
    {
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential("useremailid@gmail.com", "password");  
        smtp.EnableSsl = true;
        smtp.Send(txtfrom.Text, txtto.Text,txtsubject.Text,txtmessage.Text);

        txtto.Text = string.Empty;
        txtfrom.Text = string.Empty;
        txtsubject.Text = string.Empty;
        txtmessage.Text = string.Empty;
   
    }
}

Monday 9 July 2012

Javascript validations for Email, Phone and allow only Characters, spaces numbers in asp.net 


Introduction 
Here I will explain how to validate Email,phone number,to allow only characters and spaces and for allow only numbers using JavaScript validations in asp.net.
Description
I have a one sample registration form that contains fields like Name, Email, PhoneNo .
Now I want to check whether user enter correct email format or not, and phone number contains only numbers or not and name contains only characters and spaces or not by using JavaScript.
Here some of commonly used regular expressions
Regular Expression for Email
re=/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
Regular expression to accept only characters and spaces
re=/^[a-zA-Z ]+$/
Regular expression to accept alphanumeric and spaces
re=/^[0-9a-zA-Z ]+$/
Regular Expression to accept only numbers 
re =/^[0-9]+$/;
Regular Expression for Mobile Number
re=/\d(10)/;
Write following code in aspx page like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Vallidations Page</title>
<script language="javascript" type="text/javascript">
function validate() {
var summary = "";
summary += isvalidFirstname();
summary += isvalidEmail();
summary += isvalidphoneno();
if (summary != "") {
alert(summary);
return false;
}
else {
return true;
}
}
function isvalidphoneno() {
var uid;
var temp = document.getElementById("<%=txtphone.ClientID %>");
uid = temp.value;
var re;
re = /^[0-9]+$/;
var digits = /\d(10)/;
if (uid == "") {
return ("Please enter phoneno" + "\n");
}
else if (re.test(uid)) {
return "";
}
else {
return ("Phoneno should be digits only" + "\n");
}
}
function isvalidFirstname() {
var uid;
var temp = document.getElementById("<%=txtfname.ClientID %>");
uid = temp.value;
var re=/^[a-zA-Z ]+$/
if (uid == "") {
return ("Please enter firstname" + "\n");
}
else if (re.test(uid)) {
return "";
}
else {
return ("FirstName accepts Characters and spaces only" + "\n");
}
}
function isvalidEmail() {
var uid;
var temp = document.getElementById("<%=txtEmail.ClientID %>");
uid = temp.value;
var re = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
if (uid == "") {
return ("Please Enter Email" + "\n");
}
else if (re.test(uid)) {
return "";
}
else {
return ("Email should be in the form ex:abc@xyz.com" + "\n");
}
}
</script>
</head>
<body>
<form id="form1" runat="server"> 
<table align="center">
<tr>
<td>
<asp:Label ID="lblfname" runat="server" Text="FirstName"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Email"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCnt" runat="server" Text="Phone No"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtphone" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnsubmit" runat="server" Text="Save"
OnClientClick ="javascript:validate()" />
</td>
</tr>
</table>
</form>
</body>
</html>
Demo


Ajax Rating Control Example With Database 

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