Counting Hits on a link and save it to database

Satyapriyanayak
Posted by Satyapriyanayak under ASP.NET category on | Points: 40 | Views : 881
Create table test.
Column name as count int.
You have to insert 0 in database manually.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Textbox_gridview.WebForm2" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">Hits</asp:LinkButton>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace Textbox_gridview
{
public partial class WebForm2 : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str;
SqlCommand com;

protected void LinkButton1_Click(object sender, EventArgs e)
{
Label1.Text = (Convert.ToInt32(Label1.Text)+1).ToString();

SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "update test set count='" + Label1.Text + "'";
com = new SqlCommand(str, con);
com.ExecuteNonQuery();
con.Close();
}

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "select sum(count)from test";
com = new SqlCommand(str, con);
Label1.Text = com.ExecuteScalar().ToString();
con.Close();
}
}
}

Comments or Responses

Login to post response