zoukankan      html  css  js  c++  java
  • 回味手写三层分页

    上回写了 增删改查 没有分页的

    想了一下,现在又很多 分页模式 就找到了aspnetpager 

    感觉这个东西用着挺方便的

    用的 还是上回的代码((*^__^*) 嘻嘻……)

    先照 个全家福:

    同样还是model→ SqlHelper→Dal→BLL

    先看下model :

    Model
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace ClassModel
     7 {
     8     public class ClassModels
     9     {
    10         private int cId;
    11         public int CId
    12         {
    13             get { return cId; }
    14             set { cId = value; }
    15         }
    16         private string cName;
    17 
    18         public string CName
    19         {
    20             get { return cName; }
    21             set { cName = value; }
    22         }
    23         private int cCount;
    24 
    25         public int CCount
    26         {
    27             get { return cCount; }
    28             set { cCount = value; }
    29         }
    30         private string cImage;
    31 
    32         public string CImage
    33         {
    34             get { return cImage; }
    35             set { cImage = value; }
    36         }
    37         private bool cIsDel;
    38 
    39         public bool CIsDel
    40         {
    41             get { return cIsDel; }
    42             set { cIsDel = value; }
    43         }
    44         private DateTime cAddTime;
    45 
    46         public DateTime CAddTime
    47         {
    48             get { return cAddTime; }
    49             set { cAddTime = value; }
    50         }
    51 
    52 
    53     }
    54 }

    然后 sqlhelper:

    Sqlhelper
      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Configuration;
      6 using System.Data.SqlClient;
      7 using System.Data;
      8 
      9 namespace ClassDal
     10 {
     11     class SqlHelper
     12     {
     13         public static string connstr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
     14         public static SqlDataReader ExcuteReader(string sql, params SqlParameter[] pams)
     15         {
     16             SqlConnection conn = new SqlConnection(connstr);
     17             using (SqlCommand cmd=new SqlCommand(sql,conn))
     18             {
     19                 if (pams!=null)
     20                 {
     21                     cmd.Parameters.AddRange(pams);
     22                 }
     23                 if (conn.State==System.Data.ConnectionState.Closed)
     24                 {
     25                     conn.Open();
     26                 }
     27                 return cmd.ExecuteReader();
     28             }
     29 
     30         }
     31 
     32         public static DataTable ExcuteDataTable(string sql,params SqlParameter[] pams)
     33         {
     34             using (SqlDataAdapter adapter=new SqlDataAdapter(sql,connstr))
     35             {
     36                 if (pams!=null)
     37                 {
     38                     adapter.SelectCommand.Parameters.AddRange(pams);
     39                 }
     40                 DataTable dt = new DataTable();
     41                 adapter.Fill(dt);
     42                 return dt;
     43             }
     44         }
     45         //增删改
     46         public static int ExcuteNonQuery(string sql, params SqlParameter[] pams)
     47         {
     48             using (SqlConnection conn=new SqlConnection(connstr))
     49             {
     50                 using (SqlCommand cmd=new SqlCommand(sql,conn))
     51                 {
     52                     if (pams!=null)
     53                     {
     54                         cmd.Parameters.AddRange(pams);
     55                     }
     56                     if (conn.State==ConnectionState.Closed)
     57                     {
     58                         conn.Open();
     59                     }
     60                     return cmd.ExecuteNonQuery();
     61                 }
     62             }
     63         }
     64 
     65         public static object ExcuteScalar(string sql, params SqlParameter[] pams)
     66         {
     67             using (SqlConnection conn=new SqlConnection(connstr))
     68             {
     69                 using (SqlCommand cmd=new SqlCommand(sql,conn))
     70                 {
     71                     if (pams!=null)
     72                     {
     73                         cmd.Parameters.AddRange(pams);
     74                     }
     75                     if (conn.State==ConnectionState.Closed)
     76                     {
     77                         conn.Open();
     78                     }
     79                     return cmd.ExecuteScalar();
     80                 }
     81             }
     82         }
     83         
     84         #region 分页(由SocanCode 生成)
     85 
     86         
     87         /// <summary>
     88         /// 通用分页存储过程
     89         /// </summary>
     90         /// <param name="connectionString">连接</param>
     91         /// <param name="tblName">要显示的表或多个表的连接</param>
     92         /// <param name="fldName">要显示的字段列表,可为Null,表示*</param>
     93         /// <param name="pageSize">每页显示的记录个数</param>
     94         /// <param name="pageIndex">要显示那一页的记录</param>
     95         /// <param name="fldSort">排序字段列表或条件</param>
     96         /// <param name="Sort">排序方法,False为升序,True为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记)--程序传参如:' SortA Asc,SortB Desc,SortC ')</param>
     97         /// <param name="strCondition">查询条件,不需where,以And开始,可为Null,表示""</param>
     98         /// <param name="ID">主表的主键</param>
     99         /// <param name="Disk">是否添加查询字段的 DISTINCT 默认False不添加/True添加</param>
    100         /// <param name="pageCount">查询结果分页后的总页数</param>
    101         /// <param name="Counts">查询到的记录数</param>
    102         /// <param name="strSql">最后返回的SQL语句</param>
    103         /// <returns>查询当前页的数据集</returns>
    104         public static DataSet PageList(string connectionString, string tblName, string fldName, int pageSize, int pageIndex,
    105             string fldSort, bool Sort, string strCondition, string ID, bool Dist,
    106             out int pageCount, out int Counts, out string strSql)
    107         {
    108             SqlParameter[] parameters ={ new SqlParameter("@tblName",SqlDbType.NVarChar,200),
    109                 new SqlParameter("@fldName",SqlDbType.NVarChar,500),
    110                 new SqlParameter("@pageSize",SqlDbType.Int),
    111                 new SqlParameter("@page",SqlDbType.Int),
    112                 new SqlParameter("@fldSort",SqlDbType.NVarChar,200),
    113                 new SqlParameter("@Sort",SqlDbType.Bit),
    114                 new SqlParameter("@strCondition",SqlDbType.NVarChar,1000),
    115                 new SqlParameter("@ID",SqlDbType.NVarChar,150),
    116                 new SqlParameter("@Dist",SqlDbType.Bit),
    117                 new SqlParameter("@pageCount",SqlDbType.Int),
    118                 new SqlParameter("@Counts",SqlDbType.Int),
    119                 new SqlParameter("@strSql",SqlDbType.NVarChar,1000)};
    120 
    121             parameters[0].Value = tblName;
    122             parameters[1].Value = (fldName == null) ? "*" : fldName;
    123             parameters[2].Value = (pageSize == 0) ? int.Parse(ConfigurationManager.AppSettings["PageSize"]) : pageSize;
    124             parameters[3].Value = pageIndex;
    125             parameters[4].Value = fldSort;
    126             parameters[5].Value = Sort;
    127             parameters[6].Value = strCondition == null ? "" : strCondition;
    128             parameters[7].Value = ID;
    129             parameters[8].Value = Dist;
    130             parameters[9].Direction = ParameterDirection.Output;
    131             parameters[10].Direction = ParameterDirection.Output;
    132             parameters[11].Direction = ParameterDirection.Output;
    133 
    134             //调用存储过程
    135             DataSet ds = RunProcedure(connectionString, "PageList", parameters, "ds");
    136 
    137             pageCount = (int)parameters[9].Value;
    138             Counts = (int)parameters[10].Value;
    139             strSql = parameters[11].Value.ToString();
    140             return ds;
    141         }
    142         /// <summary>
    143         /// 执行存储过程
    144         /// </summary>
    145         /// <param name="storedProcName">存储过程名</param>
    146         /// <param name="parameters">存储过程参数</param>
    147         /// <param name="tableName">DataSet结果中的表名</param>
    148         /// <returns>DataSet</returns>
    149         public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName)
    150         {
    151             using (SqlConnection connection = new SqlConnection(connectionString))
    152             {
    153                 DataSet dataSet = new DataSet();
    154                 connection.Open();
    155                 SqlDataAdapter sqlDA = new SqlDataAdapter();
    156                 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
    157                 sqlDA.Fill(dataSet, tableName);
    158                 connection.Close();
    159                 return dataSet;
    160             }
    161         }
    162         /// <summary>
    163         /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
    164         /// </summary>
    165         /// <param name="connection">数据库连接</param>
    166         /// <param name="storedProcName">存储过程名</param>
    167         /// <param name="parameters">存储过程参数</param>
    168         /// <returns>SqlCommand</returns>
    169         private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
    170         {
    171             SqlCommand command = new SqlCommand(storedProcName, connection);
    172             command.CommandType = CommandType.StoredProcedure;
    173             if (parameters != null)
    174             {
    175                 foreach (SqlParameter parameter in parameters)
    176                 {
    177                     //if (parameter.SqlDbType == SqlDbType.DateTime)
    178                     //{
    179                     //    if ((DateTime )parameter.Value == DateTime.MinValue)
    180                     //        parameter.Value = System.DBNull.Value;
    181                     //}
    182                     if (parameter.SqlDbType == SqlDbType.DateTime)
    183                     {
    184                         if (parameter.Value == DBNull.Value)
    185                         {
    186                             parameter.Value = DBNull.Value;
    187                         }
    188 
    189                     }
    190                     command.Parameters.Add(parameter);
    191                 }
    192             }
    193             return command;
    194         }
    195         #endregion
    196     }
    197         
    198 
    199 }

    该Dal了:

    Dal
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Data;
     6 using System.Data.SqlClient;
     7 namespace ClassDal
     8 {
     9     public class ClassDals
    10     {
    11         //datetable 获取信息
    12         public DataTable GetAll()
    13         {
    14             string sql = "select *from Classes";
    15             return SqlHelper.ExcuteDataTable(sql);
    16         }
    17         // datereader 获取信息
    18         public SqlDataReader GetAllInfo()
    19         {
    20             string sql = "select *from Classes";
    21             return SqlHelper.ExcuteReader(sql);
    22         }
    23         public SqlDataReader GetInfoFromId(ClassModel.ClassModels model)
    24         {
    25             string sql = "select *from Classes where CID=@id";
    26             return SqlHelper.ExcuteReader(sql, new SqlParameter("@id", model.CId));
    27         }
    28         //删除一条信息
    29         public int DeleteInfo(int id)
    30         {
    31             string sql = "delete from Classes where CID=@cid";
    32             SqlParameter pam = new SqlParameter("@cid", id);
    33             return SqlHelper.ExcuteNonQuery(sql, pam);
    34         }
    35         //添加一条信息
    36         public int AddInfo(ClassModel.ClassModels model)
    37         {
    38 
    39             string sql = "insert into Classes(CName,CCount)values(@CName,@CCount)";
    40             SqlParameter[] pam = new SqlParameter[] {
    41             new SqlParameter("@CName",model.CName),
    42             new SqlParameter("@CCount",model.CCount)
    43             };
    44             return SqlHelper.ExcuteNonQuery(sql, pam);
    45         }
    46         //更新一条信息
    47         public int UpdateInfo(ClassModel.ClassModels model)
    48         {
    49             //update Classes set CName='123',CCount='123' where CID='43'
    50             string sql = "update Classes set CName=@name,CCount=@count where CID=@id";
    51             SqlParameter[] pams = new SqlParameter[] {
    52             new SqlParameter("@id",model.CId),
    53             new SqlParameter("@name",model.CName),
    54             new SqlParameter("@count",model.CCount)
    55             };
    56             return SqlHelper.ExcuteNonQuery(sql, pams);
    57         }
    58         //获得总数
    59         public int GetAllCount()
    60         {
    61             string sql = "  select COUNT(*) from Classes";
    62             return Convert.ToInt32(SqlHelper.ExcuteScalar(sql));
    63         }
    64         //分页
    65         public DataSet GetList(int pageSize, int pageIndex, string fldSort, bool sort, string strCondition, out int pageCount, out int count)
    66         {
    67             string strSql;
    68             DataSet ds = SqlHelper.PageList(SqlHelper.connstr, "[Classes]", null, pageSize, pageIndex, fldSort, sort, strCondition, "CID", false, out pageCount, out count, out strSql);
    69             return ds;
    70         }
    71     }
    72 }

    接下来:业务逻辑(BLL)

    BLL
      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Data;
      6 using ClassDal;
      7 using System.Data.SqlClient;
      8 
      9 namespace ClassBll
     10 {
     11     public class ClassBll
     12     {
     13         ClassDals dal = new ClassDals();
     14         /// <summary>
     15         /// 获得所有信息
     16         /// DataTable 版本
     17         /// </summary>
     18         /// <returns></returns>
     19         public List<ClassModel.ClassModels> GetAll()
     20         {
     21             DataTable da = dal.GetAll();
     22             List<ClassModel.ClassModels> list = new List<ClassModel.ClassModels>();
     23             if (da.Rows.Count > 0)
     24             {
     25                 ClassModel.ClassModels mode = null;
     26                 foreach (DataRow row in da.Rows)
     27                 {
     28                     mode = new ClassModel.ClassModels();
     29                     mode.CId = Convert.ToInt32(row["CID"].ToString());
     30                     mode.CCount = Convert.ToInt32(row["CCount"].ToString());
     31                     mode.CName = row["CName"].ToString();
     32                     list.Add(mode);
     33                 }
     34                 return list;
     35             }
     36             else
     37             {
     38                 return null;
     39             }
     40         }
     41         /// <summary>
     42         /// 获得所有信息
     43         /// DataReader 版本
     44         /// </summary>
     45         /// <returns></returns>
     46         public List<ClassModel.ClassModels> GetAllInfo()
     47         {
     48             List<ClassModel.ClassModels> list = new List<ClassModel.ClassModels>();
     49             SqlDataReader reader = dal.GetAllInfo();
     50             while (reader.Read())
     51             {
     52                 if (reader.HasRows)
     53                 {
     54                     ClassModel.ClassModels model = new ClassModel.ClassModels();
     55                     model.CId = reader.GetInt32(0);
     56                     model.CName = reader.GetString(1);
     57                     model.CCount = reader.GetInt32(2);
     58                     list.Add(model);
     59                     
     60                 }
     61             }
     62             return list;
     63         }
     64         public ClassModel.ClassModels GetInfoFromId(ClassModel.ClassModels model)
     65         {
     66            
     67             SqlDataReader reader = dal.GetInfoFromId(model);
     68             if (reader.Read())
     69             {
     70                 if (reader.HasRows)
     71                 {
     72                     model.CId = reader.GetInt32(0);
     73                     model.CName = reader.GetString(1);
     74                     model.CCount = reader.GetInt32(2);
     75                 }
     76             }
     77          
     78             return model;
     79         }
     80         public int DeleteInfo(int id)
     81         {
     82           return  dal.DeleteInfo(id);
     83         }
     84         public int AddInfo(ClassModel.ClassModels model)
     85         {
     86             return dal.AddInfo(model);
     87         }
     88         public int UpdateInfo(ClassModel.ClassModels model)
     89         {
     90             return dal.UpdateInfo(model);
     91         }
     92         public int GetAllCount()
     93         {
     94             return dal.GetAllCount();
     95         }
     96         /// <summary>
     97         /// 分页获取数据列表
     98         /// </summary>
     99         public DataSet GetList(int pageSize, int pageIndex, string fldSort, bool Sort, string strCondition, out int pageCount, out int Counts)
    100         {
    101             return dal.GetList(pageSize, pageIndex, fldSort, Sort, strCondition, out pageCount, out Counts);
    102         }
    103     }
    104 }

    这样 后台差不多 搭好了(里面有的是 socanCode生成的,本人太懒了,不想写了)

    看下前台的吧 (其实没什么好看的)

    Web 代码:

    List.aspx
     1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="List.aspx.cs" Inherits="List" EnableViewStateMac="false"  %>
     2 
     3 <%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>
     4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     5 <html xmlns="http://www.w3.org/1999/xhtml">
     6 <head runat="server">
     7     <title>学生成绩管理系统</title>
     8     <style type="text/css">
     9         #tbList
    10         {
    11             border: 1px solid blue;
    12         }
    13         #tbList th, td
    14         {
    15             border-bottom: 1px solid blue;
    16             border-right: 1px solid blue;
    17         }
    18         
    19     </style>
    20     <link href="Css/Content.css" rel="stylesheet" type="text/css" />
    21 </head>
    22 <body>
    23     <form id="form1" runat="server" method="post" action="AddInfo.aspx">
    24     <div>
    25         <asp:Repeater ID="RepeaterInfo" runat="server">
    26             <HeaderTemplate>
    27                 <table border="1" cellpadding="1" cellspacing="0">
    28                     <tr>
    29                         <th>
    30                             编号
    31                         </th>
    32                         <th>
    33                             班级名称
    34                         </th>
    35                         <th>
    36                             人数
    37                         </th>
    38                         <th colspan="3">
    39                             操作
    40                         </th>
    41                     </tr>
    42             </HeaderTemplate>
    43             <ItemTemplate>
    44                 <tr>
    45                     <td>
    46                         <%# Eval("CID") %>
    47                     </td>
    48                     <td>
    49                         <%# Eval("CName") %>
    50                     </td>
    51                     <td>
    52                         <%# Eval("CCount") %>
    53                     </td>
    54                     <td>
    55                         <a href='Update.aspx?id=" + <%# Eval("CID") %> + "'>修改</a>
    56                     </td>
    57                     <td>
    58                         <a href='Delete.ashx?id=" + <%# Eval("CID") %> + "'>删除</a>
    59                     </td>
    60                     <td>
    61                         <a href="AddInfo.aspx">添加</a>
    62                     </td>
    63                 </tr>
    64             </ItemTemplate>
    65             <FooterTemplate>
    66                 </table>
    67             </FooterTemplate>
    68         </asp:Repeater>
    69         <webdiyer:AspNetPager ID="Pager" runat="server" class="paginator" CustomInfoHTML="共%PageCount%页,当前第%CurrentPageIndex%页,每页%PageSize%条,共%RecordCount%条"
    70             EnableTheming="true" FirstPageText="首页" LastPageText="尾页" NextPageText="后页" OnPageChanged="Pager_PageChanged"
    71             PageIndexBoxType="DropDownList" PageSize="3" PrevPageText="前页" ShowCustomInfoSection="Right"
    72             ShowPageIndexBox="Always" TextAfterPageIndexBox="" TextBeforePageIndexBox="转到: " UrlPaging="True"
    73             AlwaysShow="True" CurrentPageButtonPosition="Center" CustomInfoSectionWidth="250px"
    74             CustomInfoStyle=" text-align:center;" CurrentPageButtonClass="xz ">
    75         </webdiyer:AspNetPager>
    76     </div>
    77     </form>
    78 </body>
    79 </html>
    AddInfo.aspx
     1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddInfo.aspx.cs" Inherits="AddInfo" EnableViewStateMac="false" %>
     2 
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     4 
     5 <html xmlns="http://www.w3.org/1999/xhtml">
     6 <head runat="server">
     7     <title></title>
     8 </head>
     9 <body>
    10     <form id="form1" method="post" action="AddInfo.aspx">
    11     <div>
    12        班级名称: <input type="text" name="txtCName" value="" /><br />
    13        班级人数: <input type="text" name="txtCCount" value="" /><br />
    14         <input type="hidden" name="isPostBack" value="2" />
    15         <input type="submit" name="btnAdd" value="保存" />
    16     </div>
    17     </form>
    18 </body>
    19 </html>
    Update
     1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Update.aspx.cs" Inherits="Update" EnableViewStateMac="false" %>
     2 
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     4 <html xmlns="http://www.w3.org/1999/xhtml">
     5 <head runat="server">
     6     <title></title>
     7 </head>
     8 <body>
     9     <form id="form1" method="post" action="Update.aspx">
    10     <div>
    11         班级名称:
    12         <%--用方法返回一个字符串--%>
    13         <%-- <input type="text" name="txtCName" value="<%=CCNameInfo() %>" /><br />--%>
    14         <input type="text" name="txtCName" value="<%=model.CName %>" /><br />
    15         班级人数:
    16         <input type="text" name="txtCCount" value="<%=model.CCount %>" /><br />
    17         <input type="hidden" name="isPostBack" value="<%=model.CId %>" />
    18         <input type="submit" name="btnUpdate" value="保存" />
    19     </div>
    20     </form>
    21 </body>
    22 </html>
    Delete.ashx
     1 <%@ WebHandler Language="C#" Class="Delete" %>
     2 
     3 using System;
     4 using System.Web;
     5 
     6 public class Delete : IHttpHandler {
     7     
     8     public void ProcessRequest (HttpContext context) {
     9         context.Response.ContentType = "text/html";
    10         string id=context.Request.QueryString["id"];
    11         if (!string.IsNullOrEmpty(id))
    12         {
    13             int sid = 0;
    14             if (int.TryParse(id,out sid))
    15             {
    16                 ClassBll.ClassBll bll = new ClassBll.ClassBll();
    17                 
    18                 if (bll.DeleteInfo(sid)>0)
    19                 {
    20                     context.Response.Write("<script type='text/javascript'>alert('删除成功!');window.location='List.aspx'</script>");
    21                 }
    22                 else
    23                 {
    24                     context.Response.Write("删除失败!");
    25                 }
    26             }
    27         }
    28     }
    29  
    30     public bool IsReusable {
    31         get {
    32             return false;
    33         }
    34     }
    35 
    36 }

    后台的:

    List.aspx.cs
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 using System.Web.UI;
     6 using System.Web.UI.WebControls;
     7 using System.Text;
     8 using System.Data;
     9 using System.Data.SqlClient;
    10 using System.Configuration;
    11 
    12 public partial class List : System.Web.UI.Page
    13 {
    14     public string page = "1";
    15     protected void Page_Load(object sender, EventArgs e)
    16     {
    17         if (!IsPostBack)
    18         {
    19             //BindInfo();
    20             BindData();
    21         }
    22     }
    23     protected void Pager_PageChanged(object sender, EventArgs e)
    24     {
    25         //BindInfo();
    26         BindData();
    27     }
    28     /// <summary>
    29     /// 方法一:存储过程版
    30     /// </summary>
    31     private void BindInfo()
    32     {
    33         int pageCount=0;
    34         int Counts=0;
    35         string strWhere = "";
    36         if (ViewState["strWhere"] != null)
    37         {
    38             strWhere += ViewState["strWhere"].ToString();
    39         }
    40         
    41         DataSet l = new ClassBll.ClassBll().GetList(Pager.PageSize, Pager.CurrentPageIndex, "CID", false, strWhere, out pageCount, out Counts);
    42         Pager.RecordCount = Counts;
    43         RepeaterInfo.DataSource = l;
    44         RepeaterInfo.DataBind();
    45     }
    46     
    47     /// <summary>
    48     /// 方法二:非存储过程
    49     /// </summary>
    50     public void BindData()
    51     {
    52         SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sql"].ConnectionString);
    53         string sql = "select *from Classes order by CID asc";
    54         SqlDataAdapter da = new SqlDataAdapter(sql, conn);
    55         DataSet ds = new DataSet();
    56         da.Fill(ds, Pager.PageSize * (Pager.CurrentPageIndex - 1), Pager.PageSize, "Classes");
    57         DataTable dt = ds.Tables["Classes"];
    58         Pager.RecordCount = new ClassBll.ClassBll().GetAllCount();
    59         RepeaterInfo.DataSource = dt;
    60         RepeaterInfo.DataBind();
    61     }
    62 
    63     /// <summary>
    64     /// 不带分页
    65     /// </summary>
    66     /// <returns></returns>
    67     public string GetAllInfo()
    68     {
    69         StringBuilder sb = new StringBuilder();
    70         ClassBll.ClassBll bll = new ClassBll.ClassBll();
    71         List<ClassModel.ClassModels> list = bll.GetAllInfo();
    72         foreach (ClassModel.ClassModels model in list)
    73         {
    74             sb.Append("<tr>");
    75             sb.Append("<td>" + model.CId + "</td>");
    76             sb.Append("<td>" + model.CName + "</td>");
    77             sb.Append("<td>" + model.CCount + "</td>");
    78             sb.Append("<td><a href='Update.aspx?id=" + model.CId + "'>修改</td>");
    79             sb.Append("<td><a href='Delete.ashx?id=" + model.CId + "'>删除</td>");
    80             sb.Append("</tr>");
    81         }
    82         return sb.ToString();
    83     }
    84 }

    上面的提供了两种方法 可以进行 分页,一种有存储过程的,一种无存储过程的

    剩下的就比较少了

    AddInfo.aspx.cs
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 using System.Web.UI;
     6 using System.Web.UI.WebControls;
     7 
     8 public partial class AddInfo : System.Web.UI.Page
     9 {
    10     protected void Page_Load(object sender, EventArgs e)
    11     {
    12         string name = Request.Form["txtCName"];//txtCCount  isPostBack
    13         string countstr = Request.Form["txtCCount"];
    14         string ispostBack=Request.Form["isPostBack"];
    15         if (!string.IsNullOrEmpty(ispostBack))
    16         {
    17             int count = 0;
    18             if (int.TryParse(countstr,out count))
    19             {
    20                 ClassBll.ClassBll bll = new ClassBll.ClassBll();
    21                 ClassModel.ClassModels model = new ClassModel.ClassModels();
    22                 model.CName = name;
    23                 model.CCount = count;
    24                 if (bll.AddInfo(model)>0)
    25                 {
    26                     Response.Write("<script type='text/javascript'>alert('添加成功!');window.location='List.aspx'</script>");
    27                 }
    28                 else
    29                 {
    30                     Response.Write("添加失败!");
    31                 }
    32 
    33             }
    34         }
    35     }
    36 }
    Update
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 using System.Web.UI;
     6 using System.Web.UI.WebControls;
     7 
     8 public partial class Update : System.Web.UI.Page
     9 {
    10     ClassBll.ClassBll bll = new ClassBll.ClassBll();
    11     protected  ClassModel.ClassModels model = new ClassModel.ClassModels();
    12     protected void Page_Load(object sender, EventArgs e)
    13     {
    14         string isPostback = Request.Form["isPostBack"];
    15         //如果是准备提交保存
    16         if (!string.IsNullOrEmpty(isPostback))
    17         {
    18             int idCount = 0;
    19             if (int.TryParse(isPostback,out idCount))
    20             {
    21                 string cName = Request.Form["txtCName"];// txtCName txtCCount
    22                 string cCount = Request.Form["txtCCount"];
    23                 model.CId = idCount;
    24                 model.CName = cName;
    25                 model.CCount =Convert.ToInt32(cCount);
    26                 if (bll.UpdateInfo(model)>0)
    27                 {
    28                     Response.Write("<script type='text/javascript'>alert('保存成功!');window.location='List.aspx'</script>");
    29                 }
    30                 else
    31                 {
    32                     Response.Write("修改失败!");
    33                 }
    34             }
    35         }
    36         else//如果是第一次访问
    37         {
    38             string id = Request.QueryString["id"];
    39 
    40             int idcount = 0;
    41             if (int.TryParse(id, out idcount))
    42             {
    43                 model.CId = idcount;
    44                 //查寻数据并存到model中
    45                 model = bll.GetInfoFromId(model);
    46             }
    47         }
    48 
    49 
    50 
    51     }
    52     //protected string CId()
    53     //{
    54     //    return model.CId.ToString();
    55     //}
    56     //protected string CCountInfo()
    57     //{
    58     //    return model.CCount.ToString();
    59     //}
    60     //protected string CCNameInfo()
    61     //{
    62     //    return model.CName;
    63     //}
    64 }

    存储过程:

    pagelist
      1 USE [CPS]
      2 GO
      3 /****** Object:  StoredProcedure [dbo].[PageList]    Script Date: 08/03/2012 13:51:56 ******/
      4 SET ANSI_NULLS ON
      5 GO
      6 SET QUOTED_IDENTIFIER ON
      7 GO
      8 ------------------------------------------------------------
      9 --
     10 --通用的分页存储过程
     11 --
     12 -------------------------------------------------------------
     13 Create PROCEDURE [dbo].[PageList]
     14 (
     15 @tblName     nvarchar(200),        ----要显示的表或多个表的连接
     16 @fldName     nvarchar(500) = '*',    ----要显示的字段列表
     17 @pageSize    int = 1,        ----每页显示的记录个数
     18 @page        int = 10,        ----要显示那一页的记录
     19 @fldSort    nvarchar(200) = null,    ----排序字段列表或条件
     20 @Sort        bit = 0,        ----排序方法,0为升序,1为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记)--程序传参如:' SortA Asc,SortB Desc,SortC ')
     21 @strCondition    nvarchar(1000) = null,    ----查询条件,不需where,以And开始
     22 @ID        nvarchar(150),        ----主表的主键
     23 @Dist                 bit = 0 ,          ----是否添加查询字段的 DISTINCT 默认0不添加/1添加
     24 @pageCount    int = 1 output,            ----查询结果分页后的总页数
     25 @Counts    int = 1 output,                ----查询到的记录数
     26 @strSql          nvarchar(1000) = '' output  -----最后返回的SQL语句
     27 )
     28 AS
     29 SET NOCOUNT ON
     30 Declare @sqlTmp nvarchar(1000)        ----存放动态生成的SQL语句
     31 Declare @strTmp nvarchar(1000)        ----存放取得查询结果总数的查询语句
     32 Declare @strID     nvarchar(1000)        ----存放取得查询开头或结尾ID的查询语句
     33 Declare @strSortType nvarchar(10)    ----数据排序规则A
     34 Declare @strFSortType nvarchar(10)    ----数据排序规则B
     35 Declare @SqlSelect nvarchar(50)         ----对含有DISTINCT的查询进行SQL构造
     36 Declare @SqlCounts nvarchar(50)          ----对含有DISTINCT的总数查询进行SQL构造
     37 if @Dist  = 0
     38 begin
     39     set @SqlSelect = 'select '
     40     set @SqlCounts = 'Count(*)'
     41 end
     42 else
     43 begin
     44     set @SqlSelect = 'select distinct '
     45     set @SqlCounts = 'Count(DISTINCT '+@ID+')'
     46 end
     47 if @Sort=0
     48 begin
     49     set @strFSortType=' ASC '
     50     set @strSortType=' DESC '
     51 end
     52 else
     53 begin
     54     set @strFSortType=' DESC '
     55     set @strSortType=' ASC '
     56 end
     57 --------生成查询语句--------
     58 --此处@strTmp为取得查询结果数量的语句
     59 if @strCondition is null or @strCondition=''     --没有设置显示条件
     60 begin
     61     set @sqlTmp =  @fldName + ' From ' + @tblName
     62     set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName
     63     set @strID = ' From ' + @tblName
     64 end
     65 else
     66 begin
     67     set @sqlTmp = + @fldName + 'From ' + @tblName + ' where (1>0) ' + @strCondition
     68     set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName + ' where (1>0) ' + @strCondition
     69     set @strID = ' From ' + @tblName + ' where (1>0) ' + @strCondition
     70 end
     71 ----取得查询结果总数量-----
     72 exec sp_executesql @strTmp,N'@Counts int out ',@Counts out
     73 declare @tmpCounts int
     74 if @Counts = 0
     75     set @tmpCounts = 1
     76 else
     77     set @tmpCounts = @Counts
     78     --取得分页总数
     79     set @pageCount=(@tmpCounts+@pageSize-1)/@pageSize
     80     /**//**当前页大于总页数 取最后一页**/
     81     if @page>@pageCount
     82         set @page=@pageCount
     83     --/*-----数据分页2分处理-------*/
     84     declare @pageIndex int --总数/页大小
     85     declare @lastcount int --总数%页大小 
     86     set @pageIndex = @tmpCounts/@pageSize
     87     set @lastcount = @tmpCounts%@pageSize
     88     if @lastcount > 0
     89         set @pageIndex = @pageIndex + 1
     90     else
     91         set @lastcount = @pagesize
     92     --//***显示分页
     93     if @strCondition is null or @strCondition=''     --没有设置显示条件
     94     begin
     95         if @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2   --前半部分数据处理
     96             begin 
     97                 set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName
     98                         +' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName
     99                         +' order by '+ @fldSort +' '+ @strFSortType+')'
    100                         +' order by '+ @fldSort +' '+ @strFSortType 
    101             end
    102         else
    103             begin
    104             set @page = @pageIndex-@page+1 --后半部分数据处理
    105                 if @page <= 1 --最后一页数据显示
    106                     set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@lastcount as VARCHAR(4))+' '+ @fldName+' from '+@tblName
    107                         +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
    108                 else                
    109                     set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName
    110                         +' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName
    111                         +' order by '+ @fldSort +' '+ @strSortType+')'
    112                         +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
    113             end
    114     end
    115     else --有查询条件
    116     begin
    117         if @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2   --前半部分数据处理
    118         begin 
    119                 set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName +' from  '+@tblName
    120                     +' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName
    121                     +' Where (1>0) ' + @strCondition + ' order by '+ @fldSort +' '+ @strFSortType+')'
    122                     +' ' + @strCondition + ' order by '+ @fldSort +' '+ @strFSortType                 
    123         end
    124         else
    125         begin 
    126             set @page = @pageIndex-@page+1 --后半部分数据处理
    127             if @page <= 1 --最后一页数据显示
    128                     set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@lastcount as VARCHAR(4))+' '+ @fldName+' from '+@tblName
    129                         +' where (1>0) '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType
    130             else
    131                     set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName
    132                         +' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName
    133                         +' where (1>0) '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+')'
    134                         + @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
    135         end    
    136     end
    137 ------返回查询结果-----
    138 set @strSql = @strTmp
    139 exec sp_executesql @strTmp
    140 --print @strTmp

    感觉那个样式挺好看的 复制哥 的

    http://www.cnblogs.com/zengxiangzhan/archive/2010/03/03/1677460.html

    这里是他的代码:

    Css
     1 /*拍拍网风格*/
     2 .paginator { font: 11px Arial, Helvetica, sans-serif;padding:10px 20px 10px 0; margin: 0px;}
     3 .paginator a {padding: 1px 6px; border: solid 1px #ddd; background: #fff; text-decoration: none;margin-right:2px}
     4 .paginator a:visited {padding: 1px 6px; border: solid 1px #ddd; background: #fff; text-decoration: none;}
     5 .paginator .cpb {padding: 1px 6px;font-weight: bold; font-size: 13px;border:none}
     6 .paginator a:hover {color: #fff; background: #ffa501;border-color:#ffa501;text-decoration: none;}
     7 
     8 /*淘宝风格*/
     9 .paginator { font: 12px Arial, Helvetica, sans-serif;padding:10px 20px 10px 0; margin: 0px;}
    10 .paginator a {border:solid 1px #ccc;color:#0063dc;cursor:pointer;text-decoration:none;}
    11 .paginator a:visited {padding: 1px 6px; border: solid 1px #ddd; background: #fff; text-decoration: none;}
    12 .paginator .cpb {border:1px solid #F50;font-weight:700;color:#F50;background-color:#ffeee5;}
    13 .paginator a:hover {border:solid 1px #F50;color:#f60;text-decoration:none;}
    14 .paginator a,.paginator a:visited,.paginator .cpb,.paginator a:hover  
    15 {float:left;height:16px;line-height:16px;min-width:10px;_width:10px;margin-right:5px;text-align:center;
    16  white-space:nowrap;font-size:12px;font-family:Arial,SimSun;padding:0 3px;}

    大功告成了!回家吃饭!

    O(∩_∩)O哈哈~

  • 相关阅读:
    HTML音频/视频DOM 参考手册
    HTML5 应用程序缓存 和 视频
    HTML 5 新的Input类型
    快速开发平台消息通知中心之短信发送
    设计模式之单例设计模式
    反射
    多线程之线程安全
    01-sql优化及索引
    多线程之线程状态
    shell/linux定时清理日志文件
  • 原文地址:https://www.cnblogs.com/zhaozhengyan/p/2621895.html
Copyright © 2011-2022 走看看