Thursday, December 20, 2007

Template Column VS Bound Column

This post will explain how to get information from your data grid for Template Column and Bound Column. There is so many times that when I am trying to retrieve the value of certain column from a data grid, I can get the value of the first column (Bound Column). However, I cannot get the value of the second column (Template Column). And both of the columns are not empty though.

The explanation below is what I had found out finally.

Basically, the difference between BoundColumn and TemplateColumn is that you have more control over what and how things are rendered in TemplateColumn. For example, you can decide what controls are used when editing. With Bound Column creates column bound to a field in the data source and rendered in a table cell. You can use a cell’s Text property to get whatever text is there. But please note that this only works for Bound Column.

Here is a sample of HTML code:
<asp:BoundColumn DataField="COUNTRY" HeaderText="Country">
    <HeaderStyle Font-Size="11px"></HeaderStyle>
    <ItemStyle Font-Size="10px"></ItemStyle>

<asp:TemplateColumn HeaderText="Address">
    <HeaderStyle Font-Size="11px"></HeaderStyle>
    <ItemStyle Font-Size="10px"></ItemStyle>
        <%# Container.DataItem("ADDRESS")%>
        <asp:Label id="lblAddress" Text='<%# Container.DataItem("ADDRESS")%>' Runat="server"></asp:Label>

From the HTML code as above, as you can see, the first bound column will bind the “COUNTRY” columns to its data field, while the second template column will use a Label control to bind the value into it.

Protected Sub GetColumnValue()
    'Bound Column... works
    Label1.Text = e.Item.Cells(0).Text

    'Template Column...doesn't work
Label2.Text = e.Item.Cells(1).Text
End Sub

This is because .NET sees the contents inside the Bound Column as Text and the contents inside the Template Column as a DataBoundLiteralControl (a collection of server controls).

So, to get the value of the second column, you would have to access the DataBoundLiteralControl’s Text property by using FindControl method. Here is the sample code:
Protected Sub GetColumnValue()
    Label1.Text = e.Item.Cells(0).Text

    Label2.Text = CType(e.Item.FindControl("lblAddress"), Label).Text
End Sub



Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template