Microsoft KB Archive/316672

= HOW TO: Format Data and Handle Null Values in a DataGrid Web Control =

Article ID: 316672

Article Last Modified on 2/11/2004

-

APPLIES TO


 * Microsoft ASP.NET 1.0
 * Microsoft ASP.NET 1.1

-



This article was previously published under Q316672



This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Data.SqlClient

IN THIS TASK

 * SUMMARY
 * Requirements
 * Using the DataGrid Web Control
 * To Use the DataGrid Web Control (Part 1)
 * To Use the DataGrid Web Control (Part 2)
 * Complete Code Listing
 * Code Listing for Part 1
 * Code Listing for Part 2
 * REFERENCES



SUMMARY
This article demonstrates how to create a DataGrid Web control, to bind it to a database, to handle null values, and to format the values.

Displaying data in a table by using &quot;plain&quot; HTML can be tedious to code and difficult to maintain. ASP.NET provides a DataGrid Web control that you can bind to a data source and customize to provide a fast, flexible way to display a lot of information.

Back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
 * Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows XP Professional
 * Microsoft .NET Framework
 * Microsoft Visual Studio .NET
 * Microsoft Internet Information Services (IIS) 5.0
 * Microsoft SQL Server 2000

This article assumes that you are familiar with the following topics:
 * Web applications
 * ASP.NET
 * Microsoft Visual Basic .NET

Back to the top

Using the DataGrid Web Control
ASP.NET provides a DataGrid Web control that you can bind to several different data sources. You can customize it to provide a fast, flexible way to display a lot of information. The DataGrid Web control generates the necessary HTML on the client to produce a customized table for displaying data. This article demonstrates how to create a DataGrid Web control, to bind it to a data source, to handle null values in a data source that is to be loaded into the grid, and to format data fields as they are displayed in the browser.

Back to the top

To Use the DataGrid Web Control (Part 1)
These steps create a DataGrid Web control and bind the DataGrid Web control to a data source:  Start Visual Studio .NET. Create a new ASP.NET Web Application project by using Visual Basic .NET. Name the new project DataGridControlExample.  In HTML view in WebForm1.aspx, paste the following code between the opening and closing form tags. This create a DataGrid Web control on the form that can be accessed by code on the server:   Switch to the Code window by right-clicking the window, and then clicking View Code.  Import the System.Data.SqlClient namespace. Place the following line of code at the top of the code file before the class declaration: Imports System.Data.SqlClient   Paste the following code just below the INHERITS statement in the WebForm1 class (unless this code has already been added automatically): Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid </li>  Paste the following code inside the Page_Load event procedure in the WebForm1 class. A connection to the Pubs database is made in this event. A DataSet object is populated from the Titles table by using a SQLDataAdapter object. The DataSource property of the DataGrid object is set to specify the source of the information that will be displayed in the control. The resulting DataSet object is then bound to the DataGrid1 control and displayed by using the default view that is associated with the table. The SELECT statement for the data source also modifies null price values. Instead of a null value, the code returns a price of 0 (zero):

Note You must change User ID= and Password= to the correct values before you run this code. Make sure that User ID has the appropriate permissions to perform this operation on the database.

Dim myConnString As String myConnString = &quot;Initial Catalog=pubs;server=localhost;User ID= ;Password= ;&quot; Dim myConnection As SqlConnection = New SqlConnection(myConnString) Dim myCommand As SqlCommand = New SqlCommand _ (&quot;SELECT title, ISNULL(price, 0) AS price, pubdate&quot; & _               &quot; FROM titles&quot;, MyConnection) Dim myAdapter As SqlDataAdapter = New SqlDataAdapter

myAdapter.SelectCommand = myCommand myConnection.Open

Dim myDataset As DataSet = New DataSet myAdapter.Fill(myDataset, &quot;Titles&quot;)

myConnection.Close

DataGrid1.DataSource = myDataset.Tables(&quot;Titles&quot;).DefaultView DataGrid1.DataBind Note Make sure to modify the connection string to use your SQL Server user ID and password. Also, for the code to work, make sure that the authentication is set to SQL Server and Windows in the Security section of the SQL Server properties. To view or modify the properties, start SQL Server Enterprise Manager, right-click your SQL server under the console root, and then click Properties.

</li> On the File menu, click Save All.</li> On the Debug menu, click Start to build and run the application. WebForm1 is displayed. You see a table that contains the contents of the Titles database table. All of the column headers are automatically populated with the field names. The fields appear in the order in which they occur in the table. No price column values are blank. Instead, a value of 0 (zero) is displayed. All of the other data is displayed without any special formatting.</li></ol>

Back to the top

To Use the DataGrid Web Control (Part 2)
Although the DataGrid control is easy to code and implement, this method performs only basic formatting of the data. You can use the DataBinder class to link properties of the DataGrid1 control to a DataSource column at run time, and to add formatting to that data before it is displayed in the browser. In the next example, you use the DataBinder class to format the price and pubdate field values before they are output to the browser: <ol>  In HTML view in WebForm1.aspx, replace the code between the form tags with the following HTML code. This creates a DataGrid control that does not generate columns and headers automatically from the data source. Instead, several of the data source fields are bound to the control. The price and pubdate fields are formatted at run time by using the TemplateColumn class. The TemplateColumns class contains a label control that uses the Eval method of the DataBinder class to format its contents by using a data-binding expression and a format string. The DataBinder.Eval method accepts the container, data-binding expression, and a format string:  <Columns> <asp:boundcolumn headertext=&quot;Title&quot; datafield=&quot;title&quot;/> <asp:TemplateColumn> <HeaderTemplate> Price </HeaderTemplate> <ItemTemplate> <asp:Label ID=&quot;Label2&quot; runat=&quot;server&quot; Text='<%# DataBinder.Eval(Container.DataItem, _ &quot;price&quot;, &quot;{0:c}&quot;)%>'/> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn> <HeaderTemplate> Publish Date </HeaderTemplate> <ItemTemplate> <asp:Label ID=&quot;Label1&quot; runat=&quot;server&quot; Text='<%# DataBinder.Eval(Container.DataItem, _ &quot;pubdate&quot;, &quot;{0:d}&quot;)%>'/> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> </li> On the File menu, click Save All.</li> On the Debug menu, click Start to build and run the application. WebForm1 is displayed. A table that contains only the title, price, and pubdate value for each item in the Titles table is displayed. The column headers are shown as &quot;Title,&quot; &quot;Price,&quot; and &quot;Publish Date.&quot; The price field column is formatted as currency. Null prices are replaced with &quot;$0.00.&quot; The pubdate values are formatted by using a long date format.</li> Quit the web browser.</li></ol>

Back to the top

Code Listing for Part 1
This is the code for the code-behind WebForm1.aspx.vb file:

Note You must change User ID= and Password= to the correct values before you run this code. Make sure that User ID has the appropriate permissions to perform this operation on the database.

Imports System.Data.SqlClient

Public Class WebForm1 Inherits System.Web.UI.Page

Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid

'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough> Private Sub InitializeComponent End Sub
 * 1) Region &quot; Web Form Designer Generated Code &quot;

Private Sub Page_Init(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent End Sub
 * 1) End Region

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here Dim myConnString As String myConnString = &quot;Initial Catalog=pubs;server=localhost;User ID= ;Password= ;&quot; Dim myConnection As SqlConnection = _ New SqlConnection(myConnString) Dim myCommand As SqlCommand = New SqlCommand _ (&quot;SELECT title, ISNULL(price, 0) AS price, pubdate&quot; & _               &quot; FROM titles&quot;, MyConnection) Dim myAdapter As SqlDataAdapter = New SqlDataAdapter

myAdapter.SelectCommand = myCommand myConnection.Open

Dim myDataset As DataSet = New DataSet myAdapter.Fill(myDataset, &quot;Titles&quot;)

myConnection.Close

DataGrid1.DataSource = myDataset.Tables(&quot;Titles&quot;).DefaultView DataGrid1.DataBind End Sub End Class This is the code for the WebForm1.aspx file: <%@ Page Language=&quot;vb&quot; AutoEventWireup=&quot;false&quot; Codebehind=&quot;WebForm1.aspx.vb&quot; Inherits=&quot;DataGridControlExample.WebForm1&quot;%> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot;> <HTML> <HEAD> WebForm1 <meta name=&quot;GENERATOR&quot; content=&quot;Microsoft Visual Studio.NET 7.0&quot;> <meta name=&quot;CODE_LANGUAGE&quot; content=&quot;Visual Basic 7.0&quot;> <meta name=&quot;vs_defaultClientScript&quot; content=&quot;JavaScript&quot;> <meta name=&quot;vs_targetSchema&quot; content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;> </HEAD> <body MS_POSITIONING=&quot;GridLayout&quot;> <form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot;> </asp:DataGrid> </HTML> Back to the top

Code Listing for Part 2
This is the code for the code-behind WebForm1.aspx.vb file:

Note You must change User ID= and Password= to the correct values before you run this code. Make sure that User ID has the appropriate permissions to perform this operation on the database.

Imports System.Data.SqlClient

Public Class WebForm1 Inherits System.Web.UI.Page

Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid

'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough> Private Sub InitializeComponent End Sub
 * 1) Region &quot; Web Form Designer Generated Code &quot;

Private Sub Page_Init(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent End Sub
 * 1) End Region

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here Dim myConnString As String myConnString=&quot;Initial Catalog=pubs;server=localhost;User ID= ;Password= ;&quot; Dim myConnection As SqlConnection = _ New SqlConnection(myConnString) Dim myCommand As SqlCommand = New SqlCommand _ (&quot;SELECT title, ISNULL(price, 0) AS price, pubdate&quot; & _               &quot; FROM titles&quot;, MyConnection) Dim myAdapter As SqlDataAdapter = New SqlDataAdapter

myAdapter.SelectCommand = myCommand myConnection.Open

Dim myDataset As DataSet = New DataSet myAdapter.Fill(myDataset, &quot;Titles&quot;)

myConnection.Close

DataGrid1.DataSource = myDataset.Tables(&quot;Titles&quot;).DefaultView DataGrid1.DataBind End Sub End Class This is the code for the WebForm1.aspx file: <%@ Page Language=&quot;vb&quot; AutoEventWireup=&quot;false&quot; Codebehind=&quot;WebForm1.aspx.vb&quot; Inherits=&quot;DataGridControlExample.WebForm1&quot;%> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot;> <HTML> <HEAD> WebForm1 <meta name=&quot;GENERATOR&quot; content=&quot;Microsoft Visual Studio.NET 7.0&quot;> <meta name=&quot;CODE_LANGUAGE&quot; content=&quot;Visual Basic 7.0&quot;> <meta name=&quot;vs_defaultClientScript&quot; content=&quot;JavaScript&quot;> <meta name=&quot;vs_targetSchema&quot; content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;> </HEAD> <body MS_POSITIONING=&quot;GridLayout&quot;> <form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot;>  <Columns> <asp:boundcolumn headertext=&quot;Title&quot; datafield=&quot;title&quot;/> <asp:TemplateColumn> <HeaderTemplate> Price </HeaderTemplate> <ItemTemplate> <asp:Label ID=&quot;Label2&quot; runat=&quot;server&quot; Text='<%# DataBinder.Eval(Container.DataItem, _                                            &quot;price&quot;, &quot;{0:c}&quot;)%>'/> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn> <HeaderTemplate> Publish Date </HeaderTemplate> <ItemTemplate> <asp:Label ID=&quot;Label1&quot; runat=&quot;server&quot; Text='<%# DataBinder.Eval(Container.DataItem, _                                            &quot;pubdate&quot;, &quot;{0:d}&quot;)%>'/> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> </HTML> Back to the top

<div class="references_section">