实验代码如下:
首先是模板类的抽象,继承自Page类;
实现代码如下:
public class Template : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
DataRefresh();
}
}
protected virtual void DataRefresh()
{
}
protected virtual void grid_Init(object sender, EventArgs e)
{
var grid = sender as GridView;
grid.AllowPaging = true;
grid.PageSize = 10;
grid.PagerSettings.Mode = PagerButtons.NumericFirstLast;
}
protected virtual void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
var grid = sender as GridView;
grid.PageIndex = e.NewPageIndex;
DataRefresh();
}
}
然后是一个继承此模板类的具体实例;
实现代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Child.aspx.cs" Inherits="WebTest.Child" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grid" runat="server" OnInit="grid_Init" OnPageIndexChanging="grid_PageIndexChanging"></asp:GridView>
</div>
</form>
</body>
</html>
最后就是关键的后台代码实现,此处假设需要修改grid的每页显示数和分页样式;
实现代码如下:
public partial class Child : Template
{
protected override void DataRefresh()
{
grid.DataSource = new LogDao().GetLogsByYearMonth("2012", "10");
grid.DataBind();
}
protected override void grid_Init(object sender, EventArgs e)
{
base.grid_Init(sender, e);
grid.PagerSettings.Mode = PagerButtons.NextPreviousFirstLast;
grid.PageSize = 15;
}
}
以上仅是提供一种思路,如有错误望各网友批评指正。
以上就是【用类的继承关系(重写父类的方法)实现简易后台代码模板】的全部内容了,欢迎留言评论进行交流!