如何让GridView
控件呈现<thead>
<tbody>
标签?我知道.UseAccessibleHeaders
让它 put<th>
而不是<td>
,但我不能让它<thead>
出现。
8 回答
这应该这样做:
gv.HeaderRow.TableSection = TableRowSection.TableHeader;
我在OnRowDataBound
事件中使用它:
protected void GridViewResults_OnRowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Header) {
e.Row.TableSection = TableRowSection.TableHeader;
}
}
答案中的代码需要继续Page_Load
or GridView_PreRender
。我把它放在一个被调用的方法中Page_Load
并得到一个NullReferenceException
.
我使用以下代码来执行此操作:
我添加的if
陈述很重要。
否则(取决于你如何渲染你的网格)你会抛出异常,比如:
表格必须包含按页眉、正文和页脚顺序排列的行部分。
protected override void OnPreRender(EventArgs e)
{
if ( (this.ShowHeader == true && this.Rows.Count > 0)
|| (this.ShowHeaderWhenEmpty == true))
{
//Force GridView to use <thead> instead of <tbody> - 11/03/2013 - MCR.
this.HeaderRow.TableSection = TableRowSection.TableHeader;
}
if (this.ShowFooter == true && this.Rows.Count > 0)
{
//Force GridView to use <tfoot> instead of <tbody> - 11/03/2013 - MCR.
this.FooterRow.TableSection = TableRowSection.TableFooter;
}
base.OnPreRender(e);
}
对象是我的this
GridView。
我实际上覆盖了 Asp.net GridView 来制作我自己的自定义控件,但是您可以将其粘贴到您的aspx.cs页面中并按名称引用 GridView 而不是使用自定义网格视图方法。
仅供参考:我没有测试页脚逻辑,但我知道这适用于页眉。
这对我有用:
protected void GrdPagosRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.TableSection = TableRowSection.TableBody;
}
else if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.TableSection = TableRowSection.TableHeader;
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.TableSection = TableRowSection.TableFooter;
}
}
这是在VS2010中尝试过的。
我知道这很旧,但是,对于标准的网格视图,这是对 MikeTeeVee 答案的解释:
页面:
<asp:GridView ID="GridView1" runat="server"
OnPreRender="GridView_PreRender">
aspx.cs:
protected void GridView_PreRender(object sender, EventArgs e)
{
GridView gv = (GridView)sender;
if ((gv.ShowHeader == true && gv.Rows.Count > 0)
|| (gv.ShowHeaderWhenEmpty == true))
{
//Force GridView to use <thead> instead of <tbody> - 11/03/2013 - MCR.
gv.HeaderRow.TableSection = TableRowSection.TableHeader;
}
if (gv.ShowFooter == true && gv.Rows.Count > 0)
{
//Force GridView to use <tfoot> instead of <tbody> - 11/03/2013 - MCR.
gv.FooterRow.TableSection = TableRowSection.TableFooter;
}
}
创建一个函数并在您的PageLoad
事件中使用该函数,如下所示:
功能是:
private void MakeGridViewPrinterFriendly(GridView gridView) {
if (gridView.Rows.Count > 0) {
gridView.UseAccessibleHeader = true;
gridView.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
事件PageLoad
是:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
{
MakeGridViewPrinterFriendly(grddata);
}
}
您也可以使用 jQuery 来添加它。这避免了 TableRowSection.TableHeader 在 PostBack 上被丢弃的问题。
$('#myTableId').prepend($("<thead></thead>").append($(this).find("#myTableId tr:first")));