The database table can contain columns that allow null to be
saved. In the same way we can make the typed dataset column to allow nulls by
setting the Columns property: AllowDBNull = true;
Unfortunately, typed dataset does not allow Nullable types
to be specified for a column. So we cannot specify nulls to the columns
directly, instead we should use the methods that is generated to set nulls.
How to set Nulls?
The below table gives us a picture about the method it will
generate for setting and checking nulls.
Column Name
|
Setting Null
|
Checking Null
|
UnitPrice
|
SetUnitPriceNull()
|
IsUnitPriceNull()
|
Total
|
SetTotalNull()
|
IsTotalNull()
|
.NetFramework adds methods that will set Null to a column
without the user setting it. So to set null for a column named “UnitPrice” the
method will be SetUnitPriceNull(). So the below line will set null for unitprice
column if its has null value.
Listing 9: Set a column value
if (txtUnitPrice.Text != "")
{
ProRow.UnitPrice = decimal.Parse(txtUnitPrice.Text);
}
else
{
ProRow.SetUnitPriceNull();
}
In the same way, to check whether the column has a null
value the method is ProRow.IsUnitPriceNull(); .
The above line will return either true or false depending on
the value. On calling the Add() method the constructed row can be added to the
dataset:
While accessing a value in typed dataset, we should check
for null before accessing it. Because there can be an integer column in database
that can allow nulls, accessing such column with null values will throw an
exception. We can understand this when we select null for NullValue property
for a primitive datatype in property box of a column which will throw an error
“Property value is not valid.”
So the default value will be an exception for Null value in
a column that is of a primitive type. Null values can be set to the columns of
type string. To access the “UnitPrice” column that allows null in database, the
code should be the following.
Listing 10: Get a column value
BO.Products.ProductsDataTable prod = new BO.Products.ProductsDataTable();
if(!prod[0].IsUnitPriceNull())
{
decimal price = prod[0].UnitPrice
}
Now we have constructed a typed dataset programmatically.