如何将 Colgroup 标记添加到 ASP:Datagrid 控件?

Posted

技术标签:

【中文标题】如何将 Colgroup 标记添加到 ASP:Datagrid 控件?【英文标题】:How Do I Add Colgroup Tag to ASP:Datagrid Control? 【发布时间】:2011-03-09 19:28:55 【问题描述】:

如何将 colgroup 标签添加到 datagrid 控件,以便我可以使用 css 设置每一列的样式?

【问题讨论】:

什么版本的 ASP.NET? 【参考方案1】:

我认为这已在 .NET 3.5 中得到解决,但我找不到任何参考资料。无论如何,这是一个手动服务器控件,允许您指定 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);
    


internal class ColGroup : WebControl, INamingContainer

    internal void RenderPrivate(HtmlTextWriter writer)
    
        writer.Write("<colgroup>");
        base.RenderContents(writer);
        writer.Write("</colgroup>");
    

像这样使用它...

<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>
    <!-- Rest of stuff here... -->
</custom:ColGroupGridView>

来源:Jeff Prosise's Blog

【讨论】:

如何以编程方式添加 col?例如,我想做一些类似 ColGroupGridView.ColGroup.Add(col) 或类似的事情 当然。为 _ColGroup 变量创建公共获取/设置。那么你应该可以像这样添加...Dim Col As New HtmlGenericControl("COL") Col.Attributes.Add("class", "myCssClass") ColGroupGridView.ColGroup.Add(Col) 你能解释一下 ColGroupTemplate 是什么以及我应该如何初始化它吗?到目前为止,我有这个 public void AddCol(string colClass) HtmlGenericControl col = new HtmlGenericControl("COL"); col.Attributes.Add("class", colClass); _ColGroup = 新 ColGroup(); _ColGroup.Controls.Add(col); ColGroupTemplate.InstantiateIn(_ColGroup);最后一行给了我一个未设置为对象实例的对象引用,因为 ColGroupTemplate 为空。 @Arizona1911 不要担心模板,它允许您通过标记来控制它。您需要将 _ColGroup 变量公开。这本质上是&lt;colgroup&gt; 标签,它继承了 Control 允许您在其中嵌入其他控件。您可以使用前面提到的 sn-p 将&lt;col&gt; 添加到组中。 谢谢!这将是扩展 gridview 的更有效方式。【参考方案2】:

为了动态添加列,做一个小改动怎么样?

    /// <summary>
/// Represents a Col element.
/// </summary>
public class HtmlCol : HtmlGenericControl

    /// <summary>
    /// Default constructor.
    /// </summary>
    public HtmlCol()
        : base("col")
    
    


/// <summary>
/// Collection of HtmlCols
/// </summary>
public class HtmlCols : List<HtmlCol>

    /// <summary>
    /// Default constructor.
    /// </summary>
    public HtmlCols()
    
    

    /// <summary>
    /// Adds a col to the collection.
    /// </summary>
    /// <returns></returns>
    public HtmlCol Add()
    
        var c = new HtmlCol();
        base.Add(c);
        return c;
    



/// <summary>
/// Represents a colgrpup tag element.
/// </summary>
internal class ColGroup : WebControl, INamingContainer

    internal void RenderPrivate(HtmlTextWriter writer)
    
        writer.Write("<colgroup>");
        base.RenderContents(writer);
        writer.Write("</colgroup>");
    

    internal void RenderPrivate(HtmlTextWriter writer, HtmlCols cols)
    
        writer.Write("<colgroup>");
        base.RenderContents(writer);
        foreach (var c in cols)
        
            c.RenderControl(writer);
        
        writer.Write("</colgroup>");
    



[ToolboxData("<0:PlainGrid runat=server></0:Table>")]
public class PlainGrid : GridView

    private ColGroup _colGroup = null;
    private ITemplate _colGroupTemplate = null;
    private HtmlCols _cols = null;

    [TemplateContainer(typeof(ColGroup))]
    public virtual ITemplate ColGroupTemplate
    
        get  return _colGroupTemplate; 
        set  _colGroupTemplate = value; 
    

    protected override void CreateChildControls()
    
        base.CreateChildControls();
        if (ColGroupTemplate != null)
        
            ColGroupTemplate.InstantiateIn(_colGroup);
        
    


    protected override void Render(HtmlTextWriter writer)
    
        // Get the base class's output
        var sw = new StringWriter();
        var 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, _cols);
            output = output.Insert(pos, sw.ToString());
            htw.Close();
            sw.Close();
        

        // Output the modified markup
        writer.Write(output);
    

    /// <summary>
    /// Gets/Sets col items.
    /// </summary>
    public HtmlCols Cols
    
        get  return _cols; 
        set  _cols = value; 
    

    /// <summary>
    /// Default constructor
    /// </summary>
    public PlainGrid() 
    
        base.AutoGenerateColumns = false;
        _colGroup = new ColGroup();
        _cols = new HtmlCols();
    

【讨论】:

【参考方案3】:

我已经搜索了几天来寻找有关如何将 ColGroup 模板添加到 GridView 的解决方案。使用 Josh uphere 给出的答案,以及几天阅读派生对象,尤其是 GridView,我认为更新且有效的解决方案可以帮助周围的人。

Imports System.ComponentModel
Imports System.Web.UI
Imports Microsoft.VisualBasic
Imports System.IO

Namespace CustomControls
<ToolboxData("<0:GridViewColGroup runat=server></0:GridViewColGroup>")> _
<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust"), _
ParseChildren(True)> _
Public Class GridViewColGroup
    Inherits GridView
    Implements INamingContainer

    Private _ColGroup As ColGroup = Nothing
    Private _ColGroupTemplate As ITemplate = Nothing

    <Browsable(False), _
    Description("The ColGroup template."), _
    TemplateContainer(GetType(ColGroup)), _
    PersistenceMode(PersistenceMode.InnerProperty)> _
    Public Overridable Property ColGroupTemplate() As ITemplate
        Get
            Return _ColGroupTemplate
        End Get
        Set(ByVal value As ITemplate)
            _ColGroupTemplate = value
        End Set
    End Property

    <Browsable(False), _
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
    Public Property ColGroup() As ColGroup
        Get
            Me.EnsureChildControls()
            Return _ColGroup
        End Get
        Set(ByVal value As ColGroup)
            _ColGroup = value
        End Set
    End Property

    Protected Overrides Sub CreateChildControls()
        MyBase.CreateChildControls()

        _ColGroup = New ColGroup()

        If Not ColGroupTemplate Is Nothing Then
            ColGroupTemplate.InstantiateIn(_ColGroup)
        End If

        Me.Controls.Add(_ColGroup)
    End Sub

    Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
        EnsureChildControls()
        ' Get the base class's output
        Dim sw As New StringWriter()
        Dim htw As New HtmlTextWriter(sw)
        MyBase.Render(htw)
        Dim output As String = sw.ToString()
        htw.Close()
        sw.Close()

        ' Insert a <COLGROUP> element into the output
        Dim pos As Integer = output.IndexOf("<tr")

        If pos <> -1 AndAlso _ColGroup IsNot Nothing Then
            sw = New StringWriter()
            htw = New HtmlTextWriter(sw)
            _ColGroup.RenderPrivate(htw)
            output = output.Insert(pos, sw.ToString())
            htw.Close()
            sw.Close()
        End If

        ' Output the modified markup
        writer.Write(output)
    End Sub
End Class


<ToolboxItem(False)> _
Public Class ColGroup
    Inherits WebControl
    Implements INamingContainer

    Friend Sub RenderPrivate(ByVal writer As HtmlTextWriter)
        writer.Write("<colgroup>")
        MyBase.RenderContents(writer)
        writer.Write("</colgroup>")
    End Sub
End Class

End Namespace

这确实为您提供了像 Josh sais 一样使用它的机会:

<aspcust:GridViewColGroup runat="server" ID="gridName">
    <ColGroupTemplate>
        <col class="some_class_1" />
        <col class="some_class_2" />
        ...
        <col class="some_class_n" />
    </ColGroupTemplate>
    <Columns>
        ...
    </Columns>
</aspcust:GridViewColGroup>

如果将派生类包装到命名空间中,并在 web.config 中注册如下:

<configuration>
    <system.web>
        <pages>
            <controls>
                <add tagPrefix="aspcust" namespace="CustomControls" />
            </controls >
        </pages >
    </system.web>
</configuration>

以编程方式,您可以在 ColGroup 中添加一个新列,例如 PreRender:

Protected Sub gridName_PreRender(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim grd As CustomControls.GridViewColGroup = sender
    Dim wctrl As New WebControl(HtmlTextWriterTag.Col)
    wctrl.CssClass = "some_class_m"
    grd.ColGroup.Controls.Add(wctrl)
End Sub

干杯。

【讨论】:

以上是关于如何将 Colgroup 标记添加到 ASP:Datagrid 控件?的主要内容,如果未能解决你的问题,请参考以下文章

AngularJS ng-show 在 colgroup 标签上

如何将信息窗口添加到标记事件侦听器 [重复]

我应该使用 <colgroup> 和 <col>,如果是,为啥以及如何使用?

传单:如何将文本标签添加到自定义标记图标?

如何以编程方式将标记 (UIControl) 添加到 UITextField 或 SearchBar?

如何将 CSS-Class 添加到 GoogleMaps 标记?