GridView With Cache
Hi Friends,
Here we learn how we increase the speed of our application by using caching.
Lets start what we will done.
we create a simple application where using a gridview and bind with database and using cache for speed our application.
Lets Start
The codes of .cs
using System;
using System.Data;
using System.Web.Caching;
/* Please remember to import SqlClient namespace */
using System.Data.SqlClient;
public partial class GridView_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
/* Check whether the page is post back or not */
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
if (Cache["Cache"] == null)
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|mysql.mdf;Integrated Security=True;User Instance=True");
SqlDataAdapter ad = new SqlDataAdapter("select * from sqltest", con);
DataSet ds = new DataSet();
ad.Fill(ds);
Cache.Insert("Cache", ds, null , DateTime.Now.AddMinutes(2), TimeSpan.Zero);
GridView1.DataSource = ds;
}
else
GridView1.DataSource = (DataSet)Cache["Cache"];
GridView1.DataBind();
}
}
the main codes in this is
Cache.Insert("Cache", ds, null , DateTime.Now.AddMinutes(2), TimeSpan.Zero);
The first paratmeter is the cache key used to reference the object.
The second paratmeter is the the object to be inserted in the cache.
The third parameter is the the file or cache key dependencies for the inserted object. When any dependency changes, the object becomes invalid and is removed from the cache. If there are no dependencies, this parameter contains nullNothingnullptra null reference (Nothing in Visual Basic).
The four parameter is the time at which the inserted object expires and is removed from the cache. To avoid possible issues with local time such as changes from standard time to daylight time, use UtcNow rather than Now for this parameter value. If you are using absolute expiration, the slidingExpiration parameter must be NoSlidingExpiration.
The fifth parameter is the interval between the time the inserted object is last accessed and the time at which that object expires. If this value is the equivalent of 20 minutes, the object will expire and be removed from the cache 20 minutes after it was last accessed. If you are using sliding expiration, the absoluteExpiration parameter must be NoAbsoluteExpiration.
Happy Coding !
If U Want To More Then Click Here