简体   繁体   中英

How to add a checkbox column to a control that is inherited from ASP.NET DataGrid

I've read a lot of articles about how to add a checkbox column to a DataGrid from within a page , but I can't find anything about how to add the column when inheriting the control itself.

Essentially, I know I need to create a class that inherits from ITemplate . Something along these lines:

public class SelectionCheckBoxTemplate : ITemplate {
    public void InstantiateIn(Control container)
    {
        var checkbox = new CheckBox(...);

        container.Controls.Add(checkbox);
    }
}

And then, this template needs to be added to a TemplateColumn object:

var checkBoxTemplate = new TemplateColumn();

checkBoxTemplate.ItemTemplate = new SelectionCheckBoxTemplate();

However, this is where I get stuck. All the articles now show adding this TemplateColumn object to the Page's DataGrid control. But what if I'm extending the DataGrid by inheriting from it? I tried adding this TemplateColumn to the Columns property from within OnPreRender , but nothing happens. SelectionCheckBoxTemplate 's InstantiateIn() method is never fired. Any help is appreciated. Thanks!

After a lot of digging and trying different solutions, I discovered that the column needs to be added in virtual CreateColumnSet() method. Doesn't seem like this is documented anywhere:

    protected override ArrayList CreateColumnSet(PagedDataSource source, bool useDataSource)
    {
        var columns = base.CreateColumnSet(source, useDataSource);

        var checkboxTemplate = new TemplateColumn();
        checkboxTemplate.ItemTemplate = ...;

        columns.Insert(0, checkboxTemplate);

        return columns;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM