At times, we would like the basic structure of a DataGrid, but don’t really want every field in the database table to be in its own separate column, for aesthetic purposes.
This sample uses the SQL managed provider, and the Employees table of the Northwind database to show how Template Columns in a DataGrid may be used to accomplish this task.
To do this on your own computer, just copy the code into a new ASP.Net page, and change the provider string to match your system’s needs. If you don’t have SQL Server, copy the database code to our Database Code Conversion Tool, change it over to the OleDb version, then change your provider string.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.2">
<title>Using Template Columns to Consolidate Fields</title>
<script language="VB" runat="server">
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=Your PWD;database=Northwind"
Sub Page_Load(Source as Object, E as EventArgs)
Dim MySQL as string = "Select FirstName, LastName, Title, BirthDate from Employees"
Dim MyConn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
Cmd.Fill(ds,"Employees")
MyDataGrid.Datasource=ds.Tables("Employees").DefaultView
MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>
<form runat="server" method="post">
<div align="center">
<asp:Datagrid runat="server"
Id="MyDataGrid"
GridLines="both"
Headerstyle-BackColor="#8080C0"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="14"
Headerstyle-font-bold="true"
Font-Name="Arial"
Font-Size="10"
BorderColor="Black"
autogeneratecolumns="false">
<columns>
<asp:TemplateColumn HeaderText="Name and Information">
<ItemTemplate>
<%#Container.DataItem("firstname")%> <%#Container.DataItem("lastname")%>
(<%# formatdatetime(Container.DataItem("Birthdate"),vbshortdate)%>),
<b><%#Container.DataItem("title")%></b>
</ItemTemplate>
</asp:TemplateColumn>
</columns>
</asp:DataGrid></div>
</form>
</body>
</html>