我正在使用 RowDataBound 事件对 gridview 中的数据进行条件格式更改:
void gvReg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime lastUpdate DateTime.Parse(DataBinder.Eval (e.Row.DataItem, "LAST_UPDATE");
if (lastUpdate < DateTime.Today.AddMonths(-1))
{
Hyperlink hypLastUpdate = (Hyperlink)e.Row.FindControl("hypLastUpdate";
hypLastUpdate.CssClass = "Error";
hypLastUpdate.NavigateUrl = "http://www.someExampleErrorPage.com";
}
}
}
这有效,并将正确的 CssClass 设置为超链接(这使其成为粗体红色的刺眼阴影),但是一旦对 gridview 进行排序(通过用户单击列标题),CSS 类就会在 hypLastUpdate 上重置,并且它丢失其样式和关联的 NavigateUrl 属性。
控件 hypLastUpdate 包含在 gridview 中的模板字段中,其文本值数据绑定(bind)到名为“LAST_UPDATE”的字段。
这是一个计划好的行为(排序是否应该破坏 RowDataBound 事件中完成的条件格式?)或者我可以检查一些内容以确保我没有做错什么?
我没有在后面的代码中使用 DataBind 方法,并且相关 gridview 的 View 状态已打开。
--编辑--
这最终是事件处理中的一个错误。
我在做:
gvReg.Sorted += {SomeEventHandler}
在页面加载事件内部,但仅当它不是回发时。该函数在 GridView 排序后调用 gvReg.DataBind。我删除了处理程序连线,而是将事件处理程序函数添加到 OnSorted 事件中。我猜分配给 gridview 的委托(delegate)不会在回调之间保存在 ViewState 中?
最佳答案
您好,这是我的评论含义的一个简单示例。这是我能想到的唯一方法:
protected void gvReg_Sorting(object sender, GridViewSortEventArgs e)
{
GridView gridView = (GridView)sender;
if (e.SortExpression.Length > 0)
{
foreach (DataControlField field in gridView.Columns)
{
if (field.SortExpression == e.SortExpression)
{
cellIndex = gridView.Columns.IndexOf(field);
break;
}
}
if (pSortExpression != e.SortExpression)
{
pSortDirection = SortDirection.Ascending;
}
else
{
pSortDirection = (pSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending);
}
pSortExpression = e.SortExpression;
}
//Retrieve the table from the database
pSortOrder = pSortDirection == SortDirection.Ascending ? "ASC" : "DESC";
List<Partners> partnerList = GetPartnerList();
gvReg.DataSource = partnerList;
gvReg.DataBind();
}
关于c# - Asp.net Gridview - 为什么 DataRowBound 更改在排序时丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4939273/