自定义DataControlField类

时间:2010-12-09 12:33:40

标签: asp.net gridview

我做了一些搜索,但在我的情况下没有什么是真的有用。

我想继承DataControlField(System.Web.UI.WebControls)以便能够携带两个标签控件然后我想为两个标签着色以获得某种条件格式,我有条件格式部分但我该如何自定义这个类?

我班上应该定义两个标签控件? 我将如何覆盖CreateField方法?

P.S:我知道我可以在XHTML Markup中实现这一点,但是我有很多列,在页面标记中包含这些标记是不合适的。因此,我在CodeBehind页面中这样做。

修改

public class MyField : DataControlField
{
    public MyField()
    {

    }

    protected override DataControlField CreateField()
    {
        // What to put here?
    }

    protected override void CopyProperties(DataControlField newField)
    {
        ((CalendarField)newField).DataField = this.DataField;
        ((CalendarField)newField).DataFormatString = this.DataFormatString;
        ((CalendarField)newField).ReadOnly = this.ReadOnly;

        base.CopyProperties(newField);
    }

    public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
    {
        // Call the base method
        base.InitializeCell(cell, cellType, rowState, rowIndex);

        // Initialize the contents of the cell quitting if it is a header/footer
        if (cellType == DataControlCellType.DataCell)
            InitializeDataCell(cell, rowState);
    }

    protected virtual void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
    {

    }
}

1 个答案:

答案 0 :(得分:1)

见这里。希望这会对你有所帮助。

public class MyField : DataControlField {    
    public MyField()     {      }      
    protected override DataControlField CreateField()     {         
        // What to put here?     

        return new MyField();
    }      
    protected override void CopyProperties(DataControlField newField)     {        
        ((CalendarField)newField).DataField = this.DataField;         
        ((CalendarField)newField).DataFormatString = this.DataFormatString;         
        ((CalendarField)newField).ReadOnly = this.ReadOnly;          
        base.CopyProperties(newField);     
    }      

    public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)    
    {         
        // Call the base method         
        base.InitializeCell(cell, cellType, rowState, rowIndex);          
        // Initialize the contents of the cell quitting if it is a header/footer         
        if (cellType == DataControlCellType.DataCell)
        {
            cell.DataBinding += new EventHandler(cell_DataBinding);
        }
    }

    void cell_DataBinding(object sender, EventArgs e)
    {
        Control ctrl = sender as Control;
        var container = ctrl.NamingContainer as IDataItemContainer;

        // here what you would like to show in MyField
    }      

}