How to build a GridView like DataBound Templated Custom ASP.NET Server Control

Posted by Deyan on Stack Overflow See other posts from Stack Overflow or by Deyan
Published on 2010-04-13T18:24:13Z Indexed on 2010/04/13 18:33 UTC
Read the original article Hit count: 416

I am trying to develop a very simple templated custom server control that resembles GridView. Basically, I want the control to be added in the .aspx page like this:

    <cc:SimpleGrid ID="SimpleGrid1" runat="server">
         <TemplatedColumn>ID: <%# Eval("ID") %></ TemplatedColumn>
         <TemplatedColumn>Name: <%# Eval("Name") %></ TemplatedColumn>
         <TemplatedColumn>Age: <%# Eval("Age") %></ TemplatedColumn>
    </cc:SimpleGrid>

and when providing the following datasource:

    DataTable table = new DataTable();
    table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Age", typeof(int));

    table.Rows.Add(1, "Bob", 35);
    table.Rows.Add(2, "Sam", 44);
    table.Rows.Add(3, "Ann", 26);

    SimpleGrid1.DataSource = table;
    SimpleGrid1.DataBind();

the result should be a HTML table like this one.

 -------------------------------
 | ID: 1 | Name: Bob | Age: 35 |
 -------------------------------
 | ID: 2 | Name: Sam | Age: 44 |
 -------------------------------
 | ID: 3 | Name: Ann | Age: 26 |
 -------------------------------

The main problem is that I cannot define the TemplatedColumn. When I tried to do it like this ...

    private ITemplate _TemplatedColumn;
    [PersistenceMode(PersistenceMode.InnerProperty)]
    [TemplateContainer(typeof(TemplatedColumnItem))]
    [TemplateInstance(TemplateInstance.Multiple)] 
    public ITemplate TemplatedColumn
    {
        get { return _TemplatedColumn; }
        set { _TemplatedColumn = value; }
    }

.. and subsequently instantiate the template in the CreateChildControls I got the following result which is not what I want:

 -----------
 | Age: 35 |
 -----------
 | Age: 44 |
 -----------
 | Age: 26 |
 -----------
  • I know that what I want to achieve is pointless and that I can use DataGrid to achieve it, but I am giving this very simple example because if I know how to do this I would be able to develop the control that I need. Thank you.

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about custom-server-controls