Handling Database Nulls with a DataReader

In this code sample, I use the OleDb Managed Provider (with the MS Access Biblio Database) to show how to handle Database Nulls with a Datareader. This uses a ‘helper function’ in order to handle null values at display time.

As it turns out, there weren’t many actual ‘Year Born’ dates entered into the database, so I had to add in a few just to show a varied display.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Handling Database Nulls with a DataReader</title>
	<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
	& server.mappath(".\BIBLIO.MDB") & ";"
	Dim MySQL as string = "Select author, [Year Born] from Authors"
	Dim MyConn as New OleDBConnection(strConn)
	Dim objDR as OleDBDataReader
	Dim Cmd as New OLEDBCommand(MySQL, MyConn)
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	MyDataList.DataSource = objDR
	MyDataList.DataBind()
End Sub

Function fixBirthDate(sItem) as String
if sItem is System.DBNull.Value Then
	fixBirthDate="<i><font Color=''#FF0000''>No Date Specified</font></i>"
else
	fixBirthDate="<b>" & sItem & "</b>"
End If
End function

</script>
</head>
<body>

<asp:DataList runat="server"
	Id="MyDataList"
	GridLines="Both"
	cellpadding="2"
	cellspacing="2"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="8"
	Font-Name="Arial"
	Font-Bold="false"
	RepeatDirection="Horizontal"
	RepeatColumns="4"
	Font-Size="8">
	<ItemTemplate>
		<%# Container.DataItem("Author")%> -
		<%# fixBirthDate(Container.DataItem("YearBorn"))%>
	</ItemTemplate>
</ASP:DataList>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>