日期:2014-05-17  浏览次数:20451 次

GridView代码生成的表头,为什么不能居中?
问题在注释中
C# code

   protected void gv_EmployeeP_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                //第一行表头HorizontalAlign="Center"
                TableCellCollection tcHeader = e.Row.Cells;
                tcHeader.Clear();

                //第一层表头
                tcHeader.Add(new TableHeaderCell());
                tcHeader[0].Attributes.Add("rowspan", "1");
                tcHeader[0].HorizontalAlign = HorizontalAlign.Center;//这一行为什么没起作用???
                tcHeader[0].Text = "客服";

                tcHeader.Add(new TableHeaderCell());
                tcHeader[1].Attributes.Add("colspan", "3");
                tcHeader[1].Text = "今日";
                tcHeader[1].HorizontalAlign = HorizontalAlign.Center;//这一行为什么没起作用???
                tcHeader[1].Font.Bold = true;

                tcHeader.Add(new TableHeaderCell());
                tcHeader[2].Attributes.Add("colspan", "3");
                tcHeader[2].Text = "昨日";
                tcHeader[2].HorizontalAlign = HorizontalAlign.Center;//这一行为什么没起作用???                   tcHeader[2].Font.Bold = true;

                tcHeader.Add(new TableHeaderCell());
                tcHeader[3].Attributes.Add("colspan", "3");
                tcHeader[3].HorizontalAlign = HorizontalAlign.Center;//这一行为什么没起作用???
                tcHeader[3].Text = "上月</th></tr><tr>";//第二层表头的过度
                tcHeader[3].Font.Bold = true;
              }
        }




------解决方案--------------------
不行的话就CSS搞定吧。
------解决方案--------------------
因为你上面的th里没有设置,所以默认是居左显示的。


protected void gv_EmployeeP_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//第一行表头HorizontalAlign="Center"
TableCellCollection tcHeader = e.Row.Cells;
tcHeader.Clear();

//第一层表头
tcHeader.Add(new TableHeaderCell());
tcHeader[0].Attributes.Add("rowspan", "1");
tcHeader[0].HorizontalAlign = HorizontalAlign.Center;//这一行为什么没起作用???
tcHeader[0].Text = "客服";

tcHeader.Add(new TableHeaderCell());
tcHeader[1].Attributes.Add("colspan", "3");
tcHeader[1].Text = "今日";
tcHeader[1].HorizontalAlign = HorizontalAlign.Center;//这一行为什么没起作用???
tcHeader[1].Font.Bold = true;

tcHeader.Add(new TableHeaderCell());
tcHeader[2].Attributes.Add("colspan", "3");
tcHeader[2].Text = "昨日";
tcHeader[2].HorizontalAlign = HorizontalAlign.Center;//这一行为什么没起作用??? tcHeader[2].Font.Bold = true;

tcHeader.Add(new TableHeaderCell());
tcHeader[3].Attributes.Add("colspan", "3");
tcHeader[3].HorizontalAlign = HorizontalAlign.Center;//这一行为什么没起作用???
tcHeader[3].Text = "上月</th></tr><tr>";//第二层表头的过度
tcHeader[3].Font.Bold = true;
}
}

与之对应的前面的<th align="center">
------解决方案--------------------
可能的原因是你的css里面定义了样式导致你代码写的被覆盖

th{text-align: left;}

如果你没有加样式,是绝对会居中的,测试的例子