动态设置gridview 列动态显示
1:通过js来动态改变gridview生成的html源码 添加 COL标签 组成一个带有colgroup的新table标签
2:重写gridview 因为 gridview自身不带ColGroupTemplate模板
internal class ColGroup : WebControl, INamingContainer
{
internal void RenderPrivate(HtmlTextWriter writer)
{
writer.Write("<COLGROUP>");
base.RenderContents(writer);
writer.Write("</COLGROUP>");
}
}
public class ColGroupGridView : GridView
{
private ColGroup _ColGroup = null;
private ITemplate _ColGroupTemplate = null;
[TemplateContainer(typeof(ColGroup))]
public virtual ITemplate ColGroupTemplate
{
get { return _ColGroupTemplate; }
set { _ColGroupTemplate = value; }
}
protected override void CreateChildControls()
{
base.CreateChildControls();
_ColGroup = new ColGroup();
ColGroupTemplate.InstantiateIn(_ColGroup);
}
protected override void Render(HtmlTextWriter writer)
{
// Get the base class's output
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.Render(htw);
string output = sw.ToString();
htw.Close();
sw.Close();
// Insert a <COLGROUP> element into the output
int pos = output.IndexOf("<tr");
if (pos != -1 && _ColGroup != null)
{
sw = new StringWriter();
htw = new HtmlTextWriter(sw);
_ColGroup.RenderPrivate(htw);
output = output.Insert(pos, sw.ToString());
htw.Close();
sw.Close();
}
// Output the modified markup
writer.Write(output);
}
}
使用:
<custom:ColGroupGridView ... runat="server">
<ColGroupTemplate>
<COL class="itemid" />
<COL class="cover-image" />
<COL class="title" />
<COL class="number" />
<COL class="year" />
<COL class="rating" />
<COL class="cgc-rating" />
<COL class="description" />
</ColGroupTemplate>
...
</custom:ColGroupGridView>
原文地址:http://www.wintellect.com/cs/blogs/jprosise/archive/2005/09/20/it-s-a-bit-of-a-hack-but.aspx