using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
/// <summary>
/// Summary description for entity
/// </summary>
public class entity:IComparer
{
//一些属性
private string number;
private string EXID;
private string EXName;
private string EXOperation;
private string EXOperation2;
public string Number
{
get
{
return number;
}
set
{
number = value;
}
}
public string ExID
{
get
{
return EXID;
}
set
{
EXID = value;
}
}
public string ExName
{
get
{
return EXName;
}
set
{
EXName = value;
}
}
public string ExOperation
{
get
{
return EXOperation;
}
set
{
EXOperation = value;
}
}
public string ExOperation2
{
get
{
return EXOperation2;
}
set
{
EXOperation2 = value;
}
}
public entity()
{
//
// TODO: Add constructor logic here
//
}
//定义枚举
public enum entityCompareType
{
EXID,EXName
}
private entityCompareType compareType;
//构造函数 在后面实例化这个类的时候能初始化排序的类型
public entity(entityCompareType compareType)
{
this.compareType = compareType;
}
//Compare 接口 定义方法
public int Compare(object x, object y)
{
entity P1 = (entity)x;
entity P2 = (entity)y;
switch (compareType)
{
case entityCompareType.EXID:
return P1.ExID.CompareTo(P2.ExID);
case entityCompareType.EXName:
return P1.EXName.CompareTo(P2.EXName);
default:
throw new ArgumentException("umexpected compare type");
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
下面是GridView 的Sorting 事件 此例中写了两个 一个是按照EXID排序 一个是按照EXName排序
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression.ToString();
if (sortExpression == "EXID")
{
++SortClickEXID;//一个计数器
if (SortClickEXID % 2 == 1)
{
saveData.Sort(new entity(entity.entityCompareType.EXID).Compare);
//Sort方法请查询MSDN 其中需要一个参数 比较器 在此例中 实例化entity类 然后将类中的比较器input
}
else
{
saveData.Sort(new entity(entity.entityCompareType.EXID).Compare);
saveData.Reverse();
}
}
else if(sortExpression== "EXName")
{
++SortClickEXName;//一个计数器
if (SortClickEXName % 2 == 1)
{
saveData.Sort(new entity(entity.entityCompareType.EXName).Compare);
//Sort方法请查询MSDN 其中需要一个参数 比较器 在此例中 实例化entity类 然后将类中的比较器input
}
else
{
saveData.Sort(new entity(entity.entityCompareType.EXName).Compare);
saveData.Reverse();
}
}
GridView1.DataSource = saveData;
GridView1.DataBind();
}
请注意:此例这么写接口是为了方便,扩展性并不好,如果要扩展性好,如果有几种排序方法,就应该继承几次接口。