Let's see with an example:
We are creating a table
In code behind add the following code
We are creating a table
select * from [EmployeeTest]
In the aspx file put the following code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CachingDataSet.aspx.cs" Inherits="ADONET.CachingDataSet" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gdvDataAll" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</div>
<br />
<br />
<div>
<table>
<tr>
<td>
<asp:Button runat="server" ID="btnLoadData" OnClick="btn_LoadData" Text="Load Data" />
</td>
<td>
<asp:Button runat="server" ID="btnEmptyCache" OnClick="btn_EmptyCache" Text="Empty Cache" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label runat="server" ID="lblMessage" Style="color: green; font-weight: bold"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ADONET
{
public partial class CachingDataSet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_LoadData(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["EmplyoeeDB"].ConnectionString;
using (SqlConnection sqlcon = new SqlConnection(CS))
{
if (Cache["EmployeeData"] == null)
{
SqlCommand sqlcmd = new SqlCommand("Select * from EmployeeTest", sqlcon);
SqlDataAdapter adapter
= new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
Cache["EmployeeData"]
= ds;
DataTable dt = ds.Tables[0];
gdvDataAll.DataSource = dt;
gdvDataAll.DataBind();
lblMessage.Text = "Data Loaded from database";
}
else
{
DataSet ds = (DataSet)Cache["EmployeeData"];
DataTable dt = ds.Tables[0];
gdvDataAll.DataSource = dt;
gdvDataAll.DataBind();
lblMessage.Text = "Data Loaded from Cache";
}
}
}
protected void btn_EmptyCache(object sender, EventArgs e)
{
if (Cache["EmployeeData"] != null)
{
Cache.Remove("EmployeeData");
lblMessage.Text = "Cache is now Empty";
}
else {
lblMessage.Text = "There is nothing in Cache";
}
}
}
}
0 comments:
Post a Comment