使用类扩展gridview作为控件

时间:2012-12-04 13:14:11

标签: c# asp.net

我创建了一个扩展gridview的类,将使用autogeneratecolumns=true生成的列添加到columns集合中。

using System;
using System.Data;
using System.Collections;
using System.Web.UI.WebControls;

public class GridViewEx1 : GridView
{
private DataControlFieldCollection originalColumns;

public GridViewEx1()
    : base()
{
}
public void RecordColumns()
{
    originalColumns = new DataControlFieldCollection();
    foreach (DataControlField column in Columns)
        originalColumns.Add(column as DataControlField);
}

public void ResetColumns()
{
    if (originalColumns == null)
        RecordColumns();
    else
    {
        Columns.Clear();
        foreach (DataControlField column in originalColumns)
            Columns.Add(column as DataControlField);
    }
}

protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource)
{
    ResetColumns();
    ICollection generatedColumns = base.CreateColumns(dataSource, useDataSource);
    foreach (DataControlField column in generatedColumns)
        if (!originalColumns.Contains(column))
            Columns.Add(column as DataControlField);
    return Columns;
}
}

但是我无法弄清楚如何在asp.net页面中使用这个控件?

我尝试使用原始gridview并将其初始化为

gv1 = new GridViewEx1(); // gv1 is the id of my gridview

但这只会让我的gridview完全变空。

1 个答案:

答案 0 :(得分:0)

您需要在页面上注册您的控件。

<%@ Register TagPrefix="CustomControls" Namespace="MyProject.MyControlNamespace" Assembly="MyProject" %>

<CustomControls:GridViewEx1 runat="server" />

有关注册控件的更多信息:http://weblogs.asp.net/scottgu/archive/2006/11/26/tip-trick-how-to-register-user-controls-and-custom-controls-in-web-config.aspx