Two ways of binding data to a GridView (ASP.NET)

In the following example, I will show you how to bind the same field to an ASP.NET GridView using two different methods.

In the first example, I utilize the an asp:BoundField to display the data, whereas in the second example I utilize an asp:TemplateField

Example 1 – BoundField:

[vb]

<asp:BoundField DataField=”ORDER_NUMBER” HeaderText=”Order” ReadOnly=”True” SortExpression=”ORDER_NUMBER” ItemStyle-Wrap=false />

[/vb]

Example 2 – TemplateField:

[vb]

<asp:TemplateField HeaderText=”Order” SortExpression=”OrderLineSched” ItemStyle-Wrap=”false”>
<ItemTemplate>
<asp:Label ID=”OrderLineSched” runat=”server” Text='<% #Bind(“ORDER_NUMBER”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

[/vb]

Both will display exactly the same, however the TemplateField provides greater flexibility because if, for example, you change the field type from Label to TextBox, you can make it an editable field that will actually be editable in the entire GridView (all rows).