首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

小学问(十)

2012-06-26 
小知识(十)1.virtual(虚方法)+override(重写) 与 new(覆盖)virtual+override 与 new 都能实现子类对其父类

小知识(十)

1.virtual(虚方法)+override(重写) 与 new(覆盖)

virtual+override 与 new 都能实现子类对其父类 方法的改变,但前者能实现多态性

比如 ?父类class1有方法a()、b() ?子类class2有方法c()

class1 c1=new class2();?

这时c1只能 . 点出c1.a() ?c1.b() ?这俩class1自己的方法 ??实例方法看类型

但如果父类class1有vitual a()、b() ? 子类class2有override a()、c()

?这时c1能 . 点出c1.a() ?c1.b() ?这俩方法 ? 但此时c1.a()调用的是class2中的a()方法,虚方法看对象?而class2中的a()可以完全不同于class1中的a(),从而实现多态性(指同一事物在不同的条件下可以表现出不同的形态)

以上到底是调用哪个类的a() 我们可以看here 记住 静态方法看类型、实例方法看类型、虚方法看对象?

至于new可以类似的看成是实例方法,但有些不同,如下:

 public class Class1    {        public virtual string print()        {            return "class1";        }        public void class1() { }        public virtual string class1_1() { return "class1"; }    }    public class Class2 : Class1    {        public override string print()        {            return "class2";        }    }    public class Class3 : Class2    {        public override string print()        {            return "class3";        }    }    public class Class4 : Class3    {        public new string print()        {            return "class4";        }    }    public class Class5 : Class4    {        public new string print()        {            return "class5";        }        public override string class1_1(){ return "class5";}        public void class5() { }    }

? protected void Page_Load(object sender, EventArgs e)

        {            Class5 c5 = new Class5();            Class1 c1 = c5;  //子类引用隐式转换为父类引用(将子类引用赋值给父类引用)(等同于 Class1 c1 =  new Class5(); 父类引用指向子类对象)            Label1.Text += c1.print();  //class3  这里print()不能看成虚方法,因为Class5里是用的new而不是override            Label1.Text += " " + c1.class1_1();  //class5        }

[ 插播:?一个父类class1与其子类class2,之间的转型只能是父类引用指向子类对象(或子类引用隐式转换为父类引用):

class1 c1=new class2(); ?或 class2 c2=new class2(); class1 c1=c2;

而 ?class2 c2=(class2)new class1(); ?或 class1 c1=new class1(); class2 c2=(class2)c1; ?

虽然能通过编译,但运行时会报错 ?System.InvalidCastException ]

?

我们可以看两个有继承关系的类,俩类中有相同的方法 一个是virtual 一个是override 这样才能算是虚方法看对象

而这里一个是virtual 一个是new 不能算是虚方法看对象?可以近似的看成是?实例方法看类型

但new的类型与纯实例方法不同,我们看到了c1.print()输出class3 ?而不是class1 ? 因为new要看到这个继承链中距离该类型(实例方法看类型的这个类型这里是class1) 最远的override,这里就是class3了,再远就是class4,而class4是new,如果把class2里的override改成virtual,那么将输出class1,因为class2并没有override class1的方法,所以到class1就是最远了? ? ?这里就是Class3了,其print()输出class3

现在再来看一个纯实例方法看类型

 public class Class6    {        public string print1()        {            return "class6";        }    }    public class Class7:Class6    {        public string print2()        {            return "class7";        }    }    public class Class8:Class7    {        public  string print3()        {            return "class8";        }    }

? protected void Page_Load(object sender, EventArgs e)

 {    Class8 c8 = new Class8();    Class6 c6 = c8;    Label2.Text += c6.print1();  //class6 }

?

2.GetType().GetField()

FieldInfo fi = this.GetType().GetField(字段名, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);

if(fi!=null){fi.GetValue(this);}

以上语句的意思是取得某个对象(这里是this就是当前对象)的某个公共字段(可以指定字段名,也有GetFields()方法获取对象的所有字段)并将其返回给字段信息类FieldInfo的对象fi,然后通过fi.GetValue(this)获取该对象的某个字段的值,这时就可以将该值强制转换回它本来的类型了,这时就可以操作该字段了

比如这里获取的字段本来是string[]类型? (string[])fi.GetValue(this)

如果字段类型是控件类型,比如Text? 我们就可以操作这个文本框控件的属性等了,如下:

http://topic.csdn.net/u/20080805/19/d4fcd0c2-6124-4456-8b02-968f3c4bdc4e.html

?

3.Excel导入 http://www.cnblogs.com/tonyqus/archive/2009/12/25/1631075.html

? ?1.

? ? public class ImportExcel

    {      HSSFWorkbook hssfworkbook;      /// <summary>      /// 读取指定路径的Excel表格里的全部数据      /// </summary>      /// <param name="path">Excel表格的物理路径</param>      /// <param name="sheetindex">读取哪一个sheet</param>      /// <returns>DataTable</returns>      public DataTable ReadExcel(string path,int sheetindex,int startrow)      {          using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))          {              hssfworkbook = new HSSFWorkbook(file);          }          try          {              ISheet sheet = hssfworkbook.GetSheetAt(sheetindex);              System.Collections.IEnumerator rows = sheet.GetRowEnumerator();              DataTable dt = new DataTable();              int cellcount = 0;              while (rows.MoveNext())              {                 int max=((HSSFRow)rows.Current).LastCellNum;                 if (max>cellcount)                 {                     cellcount = max;                 }              }              for (int j = 1; j < cellcount+1; j++)              {                  //dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());                  if (j==1)                  {                     dt.Columns.Add("行号/列号");                  }                  dt.Columns.Add("列"+j.ToString());              }              rows.Reset();              int currentrow = 0;              while (rows.MoveNext())              {                  currentrow++;                  if (currentrow<startrow)                  {                      continue;                  }                  HSSFRow row = (HSSFRow)rows.Current;                  DataRow dr = dt.NewRow();                  if (currentrow == startrow)                  {                      dr[0] = "";                  }                  else                  {                      dr[0] = "行"+(currentrow-startrow).ToString();                  }                  for (int i = 0; i < row.LastCellNum; i++)                  {                      ICell cell = row.GetCell(i);                      if (cell == null)                      {                          dr[i+1] = null;                      }                      else                      {                          if (currentrow == startrow)                          {                              dr[i + 1] = cell.ToString();                          }                          else                          {                              string typestr = GetType(cell.CellType);                              dr[i + 1] = cell.ToString()+"-"+(currentrow-startrow)+"行"+(i+1).ToString()+"列"+"-"+"[" + typestr + "]";                          }                      }                  }                  dt.Rows.Add(dr);              }                         return dt;          }          catch (Exception e)          {              return null;          }      }      public string GetType(CellType ct)      {          string typestr = null;          switch (ct)          {              case CellType.BLANK:                  typestr= "空白型";                  break;              case CellType.BOOLEAN:                  typestr = "布尔型";                  break;              case CellType.ERROR:                  typestr = "错误";                  break;              case CellType.FORMULA:                  typestr = "公式型";                  break;              case CellType.NUMERIC:                  typestr = "数值型";                  break;              case CellType.STRING:                  typestr = "文本型";                  break;              case CellType.Unknown:                  typestr = "Unknown";                  break;          }          return typestr;      }    }

? ? 2.

public class ExcelHelper    {        string[] DataType = null; //数据类型数组        string[] IsMust =null;    //是否必填数组         MobanItem mobandal = new MobanItem(); //填报模板(子)        /// <summary>        /// 获取上传的Excel文件数据,同时判断正确性        /// </summary>        /// <param name="sheet">ISheet对象</param>        /// <param name="startrow">开始读取行</param>        /// <param name="mbID">模板ID</param>        /// <returns>DataTable</returns>        public DataTable ReadExcel(ISheet sheet, int startrow, int mbID)        {            DataTable dtmoban = mobandal.getDetailListByMainID(mbID.ToString());            DataType = new string[dtmoban.Rows.Count];            IsMust = new string[dtmoban.Rows.Count];            //获取该模板字段的数据类型及是否为空            for (int i = 0; i < dtmoban.Rows.Count; i++)            {                   DataType[i] = dtmoban.Rows[i]["zbdataType"].ToString();                IsMust[i] = dtmoban.Rows[i]["isMust"].ToString();            }            //获取数据行            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();            DataTable dt = new DataTable();            //获取最大列数            int cellcount = 0;            while (rows.MoveNext())            {                int max = ((HSSFRow)rows.Current).LastCellNum;                if (max > cellcount)                {                    cellcount = max;                }            }            for (int j = 1; j < cellcount + 1; j++)            {                if (j == 1)                {                    dt.Columns.Add("行号/列号");                }                dt.Columns.Add("列" + j.ToString());            }            //已经rows.MoveNext(),需要Reset()回到行开始处            rows.Reset();            int currentrow = 0;              //一行行、一列列向DataTable写入数据            while (rows.MoveNext())            {                currentrow++;                if (currentrow < startrow)                {                    continue;                }                HSSFRow row = (HSSFRow)rows.Current;                DataRow dr = dt.NewRow();                if (currentrow == startrow)                {                    dr[0] = "";                }                else                {                    dr[0] = "行" + (currentrow - startrow).ToString();                }                for (int i = 0; i < row.LastCellNum; i++)                {                    ICell cell = row.GetCell(i);                    //判断是否可以为空,如果为错抛出异常(第几行第几列不能为空),调用此方法处需抓取自定义的ExcelImportException异常                    if (cell == null && IsMust[i] == "1")                    {                        throw new ExcelImportException(currentrow, i + 1, "不能为空");                    }                    else                    {                        if (currentrow == startrow)                        {                            dr[i + 1] = cell.ToString();                        }                        else                        {                            //string typestr = GetType(cell.CellType);                            string value = cell.ToString();                            string type = DataType[i];                            //判断类型是否正确,如果为错抛出异常(第几行第几列类型应该是),调用此方法处需抓取自定义的ExcelImportException异常                            //if (typestr != DataType[i])                            //{                            //    throw new ExcelImportException(currentrow, i + 1, "类型应该是" + DataType[i]);                            //}                            if (GetTypeNew(value,type)!=true)                            {                                 throw new ExcelImportException(currentrow, i + 1, "类型应该是" + DataType[i]);                            }                            dr[i + 1] = cell.ToString();                        }                    }                }                dt.Rows.Add(dr);            }            return dt;        }       public bool GetTypeNew(string value,string type)        {            bool flag = true;            switch (type)            {                case "空白型":                    flag = value == "" ? true : false;                    break;                case "数值型":                    try                    {                        decimal.Parse(value);                    }                    catch (Exception e)                    {                        flag = false;                    }                    break;                case "日期型":                    try                    {                        DateTime.Parse(value);                    }                    catch (Exception e)                    {                        flag = false;                    }                    break;                case "文本型":                        flag = true;                    break;            }            return flag;        }        public string GetType(CellType ct)        {            string typestr = null;            switch (ct)            {                case CellType.BLANK:                    typestr = "空白型";                    break;                case CellType.BOOLEAN:                    typestr = "布尔型";                    break;                case CellType.ERROR:                    typestr = "错误";                    break;                case CellType.FORMULA:                    typestr = "公式型";                    break;                case CellType.NUMERIC:                    typestr = "数值型";                    break;                case CellType.STRING:                    typestr = "文本型";                    break;                case CellType.Unknown:                    typestr = "Unknown";                    break;            }            return typestr;        }    }
public class ExcelImportException : Exception    {        public int rowNum;        public int colNum;        public string msg;        /// <summary>        /// 错误实体                    /// </summary>        /// <param name="rn">行号</param>        /// <param name="cn">列号</param>        /// <param name="errormsg">错误描述</param>        public ExcelImportException(int rn, int cn, string errormsg)        {            rowNum = rn;            colNum = cn;            msg = errormsg;        }    }

? 3? ?

         /// <summary>        ///  获取上传的企业基本信息Excel文件数据,同时判断正确性        /// </summary>        /// <param name="sheet">ISheet对象</param>        /// <param name="mbID">模板ID</param>        /// <returns>DataTable</returns>        public DataTable ReadExcel(ISheet sheet, int mbID)        {            DataTable dtmoban = mobandal.getDetailListByMainID(mbID.ToString());            DataType = new string[dtmoban.Rows.Count];            IsMust = new string[dtmoban.Rows.Count];            //获取该模板字段的数据类型及是否为空            for (int i = 0; i < dtmoban.Rows.Count; i++)            {                DataType[i] = dtmoban.Rows[i]["zbdataType"].ToString();                IsMust[i] = dtmoban.Rows[i]["isMust"].ToString();            }            //获取数据行            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();            DataTable dt = new DataTable();            //获取要导入的行号            int importRowNum = 0;
           //获取要导入的列数            int importColNum = 0;            while (rows.MoveNext())            {                try                {                    string FirstCellStr = ((HSSFRow)rows.Current).GetCell(0).ToString();                    string SecondCellStr = ((HSSFRow)rows.Current).GetCell(1).ToString();                    if (FirstCellStr == "序号" || FirstCellStr == "组织机构代码" || SecondCellStr == "组织机构代码")                    {                        importRowNum = ((HSSFRow)rows.Current).RowNum + 1;
                        importColNum = ((HSSFRow)rows.Current).LastCellNum;                        break;                    }                }                catch (Exception ex)                {                    continue;                }            }            //获取导入标题行的数据列数,构造DataTable架构            try            {                for (int j = 0; j < importColNum; j++)                {                    dt.Columns.Add("列" + j.ToString());                }            }            catch (Exception)            {                return dt;            }            //已经rows.MoveNext(),需要Reset()回到行开始处            rows.Reset();            //一行行、一列列向DataTable写入数据            while (rows.MoveNext())            {                HSSFRow row = (HSSFRow)rows.Current;                int currentRowNum = row.RowNum;                if (currentRowNum < importRowNum)                {                    continue;                }                DataRow dr = dt.NewRow();                //从导入行开始导入数据到DataTable  加了序号i要从1开始 DataType数组与IsMust数组下标要减1                ICell cellxh = row.GetCell(0); //获取该行的序号                for (int i = 1; i <  importColNum; i++)                {                    ICell cell = row.GetCell(i);                    //判断是否可以为空,如果为错抛出异常(第几行第几列不能为空),调用此方法处需抓取自定义的ExcelImportException异常                    if (cell == null && IsMust[i - 1] == "1")                    {                        throw new ExcelImportExceptionNew("Sheet[" + sheet.SheetName + "]", "序号[" + cellxh.ToString() + "]", "列名[" + sheet.GetRow(importRowNum - 1).GetCell(i).ToString() + "]", "错误信息[不能为空]");                    }//可以为空                    else if (cell == null && IsMust[i - 1] != "1")                    {                        dr[i] = "";                    }                    else                    {                        string value = cell.ToString();                        string type = DataType[i - 1];                        if (GetTypeNew(value, type) != true)                        {                            throw new ExcelImportExceptionNew("Sheet[" + sheet.SheetName + "]", "序号[" + cellxh.ToString() + "]", "列名[" + sheet.GetRow(importRowNum - 1).GetCell(i).ToString() + "]", "错误信息[类型应该是" + DataType[i] + "]");                        }                        dr[i] = cell.ToString();                    }                }                dt.Rows.Add(dr);            }            dt.Columns.RemoveAt(0); //去掉序号列            return dt;        }

? 4 ?不是遇到错误就停止,而是将所有错误都展示出来 传入的初始txtErrorInfo为?错误信息:\r\n

         /// <summary>        ///  获取上传的企业基本信息Excel文件数据,同时判断正确性        /// </summary>        /// <param name="sheet">ISheet对象</param>        /// <param name="mbID">模板ID</param>        /// <param name="txtErrorInfo">客户端显示所有错误信息字符串</param>        /// <returns>DataTable</returns>        public DataTable ReadExcel(ISheet sheet, int mbID,ref string txtErrorInfo)        {            DataTable dtmoban = mobandal.getDetailListByMainID(mbID.ToString());            DataType = new string[dtmoban.Rows.Count];            IsMust = new string[dtmoban.Rows.Count];            //获取该模板字段的数据类型及是否为空            for (int i = 0; i < dtmoban.Rows.Count; i++)            {                DataType[i] = dtmoban.Rows[i]["zbdataType"].ToString();                IsMust[i] = dtmoban.Rows[i]["isMust"].ToString();            }            //获取数据行            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();            DataTable dt = new DataTable();            //获取要导入的行号            int importRowNum = 0;            //获取要导入的列数            int importColNum = 0;            while (rows.MoveNext())            {                try                {                    string FirstCellStr = ((HSSFRow)rows.Current).GetCell(0).ToString();                    string SecondCellStr = ((HSSFRow)rows.Current).GetCell(1).ToString();                    if (FirstCellStr == "序号" || FirstCellStr == "组织机构代码" || SecondCellStr == "组织机构代码")                    {                        importRowNum = ((HSSFRow)rows.Current).RowNum + 1;                        importColNum = ((HSSFRow)rows.Current).LastCellNum;                        break;                    }                }                catch (Exception ex)                {                    continue;                }            }            //获取导入标题行的数据列数,构造DataTable架构            try            {                for (int j = 0; j < importColNum; j++)                {                    dt.Columns.Add("列" + j.ToString());                }            }            catch (Exception)            {                return dt;            }            //已经rows.MoveNext(),需要Reset()回到行开始处            rows.Reset();            //一行行、一列列向DataTable写入数据            while (rows.MoveNext())            {                HSSFRow row = (HSSFRow)rows.Current;                int currentRowNum = row.RowNum;                if (currentRowNum < importRowNum)                {                    continue;                }                DataRow dr = dt.NewRow();                //从导入行开始导入数据到DataTable  加了序号i要从1开始 DataType数组与IsMust数组下标要减1                ICell cellxh = row.GetCell(0); //获取该行的序号                for (int i = 1; i < importColNum; i++)                {                    ICell cell = row.GetCell(i);                    //判断是否可以为空,如果为错抛出异常(第几行第几列不能为空),调用此方法处需抓取自定义的ExcelImportException异常                    if (cell == null && IsMust[i - 1] == "1")                    {                        //throw new ExcelImportExceptionNew("Sheet[" + sheet.SheetName + "]", "序号[" + cellxh.ToString() + "]", "列名[" + sheet.GetRow(importRowNum - 1).GetCell(i).ToString() + "]", "错误信息[不能为空]");                        txtErrorInfo += sheet.SheetName + "|序号" + cellxh.ToString() + "|列名" + sheet.GetRow(importRowNum - 1).GetCell(i).ToString() + "|不能为空\r\n";                    }//可以为空                    else if (cell == null && IsMust[i - 1] != "1")                    {                        dr[i] = "";                    }                    else                    {                        string value = cell.ToString();                        if (value=="")                        {                             txtErrorInfo += sheet.SheetName + "|序号" + cellxh.ToString() + "|列名" + sheet.GetRow(importRowNum - 1).GetCell(i).ToString() + "|不能为空\r\n";                        }                        string type = DataType[i - 1];                        if (GetTypeNew(value, type) != true)                        {                            //throw new ExcelImportExceptionNew("Sheet[" + sheet.SheetName + "]", "序号[" + cellxh.ToString() + "]", "列名[" + sheet.GetRow(importRowNum - 1).GetCell(i).ToString() + "]", "错误信息[类型应该是" + DataType[i] + "]");                            txtErrorInfo += sheet.SheetName + "|序号" + cellxh.ToString() + "|列名" + sheet.GetRow(importRowNum - 1).GetCell(i).ToString() + "|类型应该是" + DataType[i] + "\r\n";                        }                        dr[i] = cell.ToString();                    }                }                dt.Rows.Add(dr);            }            dt.Columns.RemoveAt(0); //去掉序号列            if (txtErrorInfo.Length> 9) //错误信息:\r\n            {                dt.Clear();            }            return dt;        }
?

?

?

4. .net中出现单击Button按钮不执行单击事件

这种情况很可能是因为Button按钮所在的页面有两个或两个以上的Form标签

?

5. 公司分页方法(二)

用到了用户控件,其上面可放置要分页的Reapter、GridView等...

? ?<div align="right" style="width: 98%">

? ? ?<uc1:PageNavigator ID="PageNavigator1" runat="server" />

? ?</div>

其HTML代码如下:

<%@ Control Language="C#" AutoEventWireup="true" Inherits="controls_PageNavigator" Codebehind="PageNavigator.ascx.cs" %>共<asp:Label runat="server" ID="LblRecordCount"/>条记录,共<asp:Label runat="server" ID="LblPageCount"/>页,当前第<asp:Label runat="server" ID="LblPageIndex" />页 <asp:LinkButton ID="LnkBtnFirst" runat="server" CommandName="Page" OnClick="LnkBtnFirst_Click" Cssrunat="server" CommandName="Page" OnClick="LnkBtnPrevious_Click" Cssrunat="server" CommandName="Page" OnClick="LnkBtnNext_Click" Cssrunat="server" CommandName="Page" OnClick="LnkBtnLast_Click" Cssrunat="server" width="20px" Cssrunat="server" causesvalidation="False" commandargument="-1" commandname="Page" text="Go" OnClick="LnkBtnGoto_Click" Css/>

?其后台代码如下:

using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public delegate void PageChangeHandler(object send, int nPageIndex); //定义了一个委托public partial class controls_PageNavigator : System.Web.UI.UserControl{    //定义了一个基于上面委托的事件,在需要该用户控件的页面的Page_Load方法里需要给该事件注册一个方法,看下面的LnkBtnFirst_Click等方法,每当点击它们就会触发该事件从而执行注册的那个方法    public event PageChangeHandler OnPageChange;    private int _PageCount = 0;    private int _RecordCount = 0;    private int _PageIndex = 1;    protected void Page_Load(object sender, EventArgs e)    {    }    public int PageCount    {        get         {            return int.Parse(this.LblPageCount.Text);        }        set         {            _PageCount = value;            /*            if (_PageCount < 2)            {                //this.txtNewPageIndex.Enabled = false;                //this.LnkBtnGoto.Enabled = false;            }            else            {                //this.txtNewPageIndex.Enabled = true;                //this.LnkBtnGoto.Enabled = true;            }             */            this.LblPageCount.Text = _PageCount.ToString();        }    }    public int RecordCount    {        get        {            return int.Parse(this.LblRecordCount.Text);        }        set        {            _RecordCount = value;            this.LblRecordCount.Text = _RecordCount.ToString();        }    }    public int PageIndex    {        get        {            return int.Parse(this.LblPageIndex.Text);        }        set        {            _PageIndex = value;            this.txtNewPageIndex.Text = this.LblPageIndex.Text = _PageIndex.ToString();            if (_PageIndex < 2)            {                this.LnkBtnFirst.Enabled = false;                this.LnkBtnPrevious.Enabled = false;            }            else            {                this.LnkBtnFirst.Enabled = true;                this.LnkBtnPrevious.Enabled = true;            }            if (_PageIndex >= _PageCount)            {                this.LnkBtnNext.Enabled = false;                this.LnkBtnLast.Enabled = false;            }            else            {                this.LnkBtnNext.Enabled = true;                this.LnkBtnLast.Enabled = true;            }        }    }    protected void LnkBtnFirst_Click(object sender, EventArgs e)    {        try        {            OnPageChange(sender, 1);        }        catch { }    }    protected void LnkBtnPrevious_Click(object sender, EventArgs e)    {        try        {            int n = Convert.ToInt32(this.LblPageIndex.Text);            n--;            OnPageChange(sender, n);        }        catch        {            throw;        }    }    protected void LnkBtnNext_Click(object sender, EventArgs e)    {        try        {            int n = Convert.ToInt32(this.LblPageIndex.Text);            n++;            OnPageChange(sender, n);        }        catch         {            throw;        }    }    protected void LnkBtnLast_Click(object sender, EventArgs e)    {        try        {            int n = Convert.ToInt32(this.LblPageCount.Text);            OnPageChange(sender, n);        }        catch        {            throw;        }    }    protected void LnkBtnGoto_Click(object sender, EventArgs e)    {        int n;        try        {            n = Convert.ToInt32(this.txtNewPageIndex.Text);        }        catch         {            n = Convert.ToInt32(this.LblPageIndex.Text);        }        int np = Convert.ToInt32(this.LblPageCount.Text.Trim());        if (n > np)            n = np;        if (n < 1)            n = 1;        OnPageChange(sender, n);    }}

使用PageNavigator页的后台代码如下:

protected void Page_Load(object sender, EventArgs e) {       this.PageNavigator1.OnPageChange += new PageChangeHandler(PageNavigator1_OnPageChange);       if (!Page.IsPostBack)       {          DataListBind(1);       } }void PageNavigator1_OnPageChange(object send, int nPageIndex){     DataListBind(nPageIndex);}private void DataListBind(int PageIndex) {     int nRCount, nPCount;      //获取分页的DataTable     string SqlAllFields="id,name,age,sex"; //要查询的字段     string SqlTablesAndWhere="tablename where **"; //表名及where语句     string IndexField="id"; //主键字段     string OrderFields="order by id desc"; //排序语句     DataTable dt = GetPage(SqlAllFields,SqlTablesAndWhere,IndexField,OrderFields,PageIndex, 20, out nRCount, out nPCount);     this.PageNavigator1.PageCount = nPCount;     this.PageNavigator1.PageIndex = PageIndex;     this.PageNavigator1.RecordCount = nRCount;     this.Repeater1.DataSource = dt;     this.Repeater1.DataBind();     dt.Clear();     dt.Dispose(); }

上面的GetPage方法如下:

public  DataTable GetPage(string sqlallfields,string sqltablesandwhere ,string indexfield,string orderfields,int PageIndex, int PageSize, out int RecordCount, out int PageCount){        string Sql = GetPageSql(SqlAllFields, SqlTablesAndWhere, IndexField, OrderFields, PageIndex, PageSize, out  RecordCount, out  PageCount);    //然后执行sql语句返回DataTable}

?上面的FetPageSql方法如下:

private  string GetPageSql(string SqlAllFields, string SqlTablesAndWhere, string IndexField, string OrderFields, int PageIndex, int PageSize, out int RecordCount, out int PageCount)        {            RecordCount = 0;            PageCount = 0;            if (PageSize <= 0)            {                PageSize = 10;            }            string SqlCount = "select count(" + IndexField + ") from " + SqlTablesAndWhere;                      RecordCount = SqlCount查出总记录数;            if (RecordCount % PageSize == 0)            {                PageCount = RecordCount / PageSize;            }            else            {                PageCount = RecordCount / PageSize + 1;            }            if (PageIndex > PageCount)                PageIndex = PageCount;            if (PageIndex < 1)                PageIndex = 1;            string Sql = null;            if (PageIndex == 1)            {                Sql = "select top " + PageSize + " " + SqlAllFields + " from " + SqlTablesAndWhere + " " + OrderFields;            }            else            {                Sql = "select top " + PageSize + " " + SqlAllFields + " from ";                if (SqlTablesAndWhere.ToLower().IndexOf(" where ") > 0)                {                    string _where = Regex.Replace(SqlTablesAndWhere, @"\ where\ ", " where (", RegexOptions.IgnoreCase | RegexOptions.Compiled);                    Sql += _where + ") and (";                }                else                {                    Sql += SqlTablesAndWhere + " where (";                }                Sql += IndexField + " not in (select top " + (PageIndex - 1) * PageSize + " " + IndexField + " from " + SqlTablesAndWhere + " " + OrderFields;                Sql += ")) " + OrderFields;            }            return Sql;        }
?

?

?

?

热点排行