我和.net

主要讲述Sharepoint以及OfficeSystem和在.net下的开发和应用

导航

感受DataGrid给数据操作带来的便利(6)

 

第六节:按列排序

我们在使用数据时,常常要对数据进行排序,那么在这方面DataGrid为我们提供了什么呢?是不是像其他功能那样很轻松就可以实现呢?我刚刚体验了一下,答案是:真的很简单。

首先,我要设置DataGrid的属性,允许它排序,属性名称是:AllowSorting,默认是False,我们设置为True,这个时候,如果你编译运行的话,你就会发现每一列的标题都加上了超链接。不过,这个时候,你点击这些标题并没有什么反应,这是因为,你还没有为这些事件编写代码。我们到属性窗口创建事件OnSortCommand()——单击列标题排序时候发生的事件。

你可以直接在这个函数中编写用于DataGrid重新绑定数据的代码,我呢,这里还是想改造一下我前面一直在用的函数BindGrid()。

首先,我要给它增加一个参数,用于告诉程序,应该按照哪个列来排序,我的函数编程了BindGridstring sortField

然后呢,我要增加一个DataView来对数据进行排序。我们来看详细的代码,注意,改动的部分,我用红色标出来:

public void BindGrid(string strSortField)

{

string selectCmd="select 流水号 as id,姓名 as name,公司 as Company from sheet1$";

SqlDataAdapter mycomm=new SqlDataAdapter(selectCmd,cn);

DataSet ds=new DataSet();

mycomm.Fill(ds,"sheet1$");

DataView Source=ds.Tables["Sheet1$"].DefaultView;

Source.Sort=strSortField;

DataGrid1.DataSource=Source;///ds.Tables["sheet1$"].DefaultView;//原来是直接把Ds的数据给DataSource

DataGrid1.DataBind();

}

 

我们在OnSrotCommand事件中应用这个函数:

private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)

{

         //参数e用于传递列名

BindGrid(e.SortExpression);

 

}

 

如果我们要按倒序或者按顺序排序,我们可以加上“ ASC 或“ DESC”,如:

private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)

{

         //参数e用于传递列名

BindGrid(e.SortExpression+" DESC");

 

}

 

我们经常会有这样的需求,单击一下列标题,顺序排序,再单击一下列标题,逆序排序,下列代码来完成这样的事情:

private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)

{

 

DataGrid1.CurrentPageIndex=0;

if(Label1.Text=="1")//web程序中,我喜欢用控件来保存全局变量

{

BindGrid(e.SortExpression+" DESC");

Label1.Text="0";

}

else

{

BindGrid(e.SortExpression+" ASC");

Label1.Text="1";

 

           }

 

}

 

 

posted on 2004-11-18 08:07  皮皮  阅读(988)  评论(0编辑  收藏  举报