设置TableSection = TableRowSection.TableHeader
最初绑定(bind)网格后,将标题行放入 thead
.回发后(网格未重新绑定(bind)),标题行恢复为表格正文。我希望标题行保持领先;有人可以解释为什么不是这种情况或我做错了什么吗?
样本:
单击该按钮可进行回发。回发后 header 不是橙色,因为它不在 thead
中了。
aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="gridtest.aspx.cs" Inherits="ffff.gridtest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
thead th { background-color:Orange;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div><asp:Button ID="Button1" runat="server" Text="Button" />
this button is here just to trigger a postback</div>
<asp:GridView ID="gv1" runat="server"></asp:GridView>
</form>
</body>
</html>
代码
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ffff
{
public partial class gridtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gv1.DataBound += new EventHandler(gv1_DataBound);
if (!IsPostBack) { BindGrid(); }
}
void Page_PreRender(object sender, EventArgs e)
{
if (gv1.HeaderRow != null)
System.Diagnostics.Debug.WriteLine(gv1.HeaderRow.TableSection); // still TableHeader after postback
}
void gv1_DataBound(object sender, EventArgs e)
{
if (gv1.HeaderRow != null)
{
gv1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
private void BindGrid()
{
gv1.DataSource = this.Page.Controls;
gv1.DataBind();
}
}
}
最佳答案
改为使用 Pre_Render_Complete 事件来添加表格部分。这将确保 thead
始终添加部分。正如您目前在 DataBound 上所做的那样,只有在绑定(bind)数据时才会添加该部分。
protected override void OnPreRenderComplete(EventArgs e)
{
if (gv1.Rows.Count > 0)
{
gv1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
随意更改我用来检查标题行的行检查,就像您目前所做的那样。
关于asp.net - 为什么GridView在回发后不将标题行呈现为thead?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6618950/