前台
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
连接数据库
<connectionStrings>
<add name ="sqlserverstr" connectionString ="Data Source=IDEA-PC\MSSQ;Initial Catalog=MyTest;User ID=sa;Password=***"></add>
</connectionStrings>
后台
static List<Acticle> list=new List<Acticle>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Loadsender();
}
}
#region 缓存方法一
private void Loadsender()
{
string s = ConfigurationManager.ConnectionStrings["sqlserverstr"].ConnectionString;
DataTable dt = new DataTable();
if (Cache["Username"] == null)
{
using (SqlConnection con = new SqlConnection(s))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select * from Studentwork";
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
//Cache["Username"] = dt;
//时间设置
Cache.Insert("article", dt, null, DateTime.UtcNow.AddSeconds(30), TimeSpan.Zero);
}
}
else
{
dt = Cache["Username"] as DataTable;
}
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
#endregion
#region 缓存方法二
private void Loadsender()
{
string s = ConfigurationManager.ConnectionStrings["sqlserverstr"].ConnectionString;
DataTable dt = new DataTable();
if (list.Count == 0)
{
using (SqlConnection con = new SqlConnection(s))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select * from Studentwork";
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
foreach (DataRow row in dt.Rows)
{
Acticle acticle = new Acticle();
acticle.Workcity = row["Workcity"].ToString();
acticle.Workadd = row["Workadd"].ToString();
acticle.SYpay = row["SYpay"].ToString();
acticle.ZZpay = row["ZZpay"].ToString();
acticle.Mealallowance = row["Mealallowance"].ToString();
acticle.Carallowance = row["Carallowance"].ToString();
acticle.Username = row["Username"].ToString();
list.Add(acticle);
}
}
}
else
{
}
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
#endregion
方法二需建一个类文件
public class Acticle
{
public string Workcity {get;set;}
public string Employer {get;set;}
public string Workadd {get;set;}
public string SYpay {get;set;}
public string ZZpay {get;set;}
public string Mealallowance {get;set;}
public string Carallowance {get;set;}
public string Username { get; set; }
}