c#asp.net网格视图未排序
本文关键字:排序 视图 网格 net c#asp | 更新日期: 2023-09-27 17:57:49
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using BiscomFax;
namespace FaxServer
{
public partial class _Default : System.Web.UI.Page
{
public const string vsColumn = "Column";
public const string vsSortDirection = "SortDirection";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
ViewState[vsColumn] = "";
List_Click(ActivityButton, e);
}
protected void List_Click(object sender, EventArgs e)
{
//using (new Impersonator("administrator", "mlabs.com", "100%secure*"))
//{
try
{
Fax fax = new Fax();
ConnObj cnObj = GetConfiguration();
Button btn = (Button)sender;
string sort = "";
DataTable dt = new DataTable();
switch (btn.CommandName)
{
case "Activity":
sort = "DateTime";
dt = fax.GetActivityLog(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
case "Message":
sort = "DateTime";
dt = fax.GetMessageStatus(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
case "Pending":
sort = "DeliveryTime";
dt = fax.GetPendingList(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
default:
sort = "DateTime";
dt = fax.GetActivityLog(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
}
GridView1.DataSource = dt;
GridView1.Sort(sort, SortDirection.Descending);
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
//}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GridView1.DataSource as DataTable;
if (dt != null)
{
DataView dv = new DataView(dt);
string oldSort = ViewState[vsColumn].ToString();
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(e.SortDirection);
if (dv.Sort == oldSort)
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(SortDirection.Descending);
ViewState[vsColumn] = dv.Sort;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
我很难排序这个网格视图的内容,我知道我绑定正确,因为数据正在显示,但数据根本没有按DateTime排序。我做错了什么?
让我们看看这行
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(e.SortDirection);
测试时,当您在这行上放置断点时,e.SortExpression
的值是多少?
您的数据绑定是正确的。以下是一篇在gridview中进行排序的好文章:http://www.mikepope.com/blog/DisplayBlog.aspx?permalink=1418
[更新]
您的代码有几个不一致之处。您可能需要再次实施它。
- allowsorting必须为true
- 每个网格列都必须声明排序表达式
- 无法从gridview的数据源读回数据
- 您需要在每次回发时从数据库中读取数据,即排序
下面是C#中的一个很好的例子:http://programming.top54u.com/post/ASP-Net-2-0-Gridview-Sorting-Using-C-sharp.aspx
您可以通过设置数据表的属性datatable.defaultview.sort
对其进行排序。不过,我根本不知道之后是需要绑定数据表还是datatable.defaultview
。
尝试此代码
protected void grdList1_Sorting(object sender, GridViewSortEventArgs e)
{
fillgrid();
string sortstr = e.SortExpression;
DataView dview = new DataView(dtable);
if (sortstr == "asc")
dview.Sort = e.SortExpression + " desc";
else
dview.Sort = e.SortExpression + " asc";
grdList1.DataSource = dview;
grdList1.DataBind();
}
只需检查gridview控件中aspx页面上的allowsorting属性
这可能是假的。
请确认,然后检查排序。