Sei sulla pagina 1di 9

Introduction

Typed DataSet provides strongly typed access to its containing tables and columns.
Dataset and Typed Dataset
ds.Tables["0"].Rows[0][0].ToString();

or
ds.Tables["Customers"].Rows[0]["Name"].ToString();

The same can be accessed in typed dataset as:


ds.Customers[0].Name;

Advantages
• The difference between DataSet and Typed DataSet is, schema already present for the
Typed DataSet. Hence any mismatch in the column data type will generate Compile time
errors rather than Runtime errors as in the case of DataSet(normal one). In other words, it
provides strongly typed access to its containing tables and columns

Normal DataSet:
//Assign a value to the first column
dsEmp.Tables["EMPLOYEE"].Rows[0][0] = "12345";//This will generate runtime
error as empno column is integer

Typed DataSet:
dsEmp.EMPLOYEE[0].empno = "12345";//This will generate compile time error.

• Also accessing the column value is much easier than the normal dataset as the column
definition will be available in the schema.

Normal DataSet:
//Let us print first row and first column of the table
Console.Write(dsEmp.Tables["EMPLOYEE"].Rows[0][0].ToString());

Typed Dataset:
Console.Write(dsEmp.EMPLOYEE[0].empno.ToString());

I am using NorthWind database to explain typed dataset in this article.

Creating typed dataset


1) Open a web application project in Visual Studio 2005.
2) To add a typed dataset, right click the solution and click “Add New Item.” It will open a new
item dialog box like below.
Figure 1 – Add New Item
3) Select Dataset and change the name; click Add.
4) Open the server explorer in visual studio. If you cannott find the server explorer, click “Server
Explorer" from the view menu of visual studio.
5) It will open Add Connection window. Select the Server name and select the “NorthWind”
database or your own database as below.
Figure 2 – Add Connection

Select Server name, select the database name and click OK.
6) Drag and drop the Employees table into the dataset designer to create the typed dataset from the
server explorer. The designer will look like figure 3.
Figure 3 – Dataset Designer
By default, it will have a TableAdapter (EmployeesTableAdapter here) with Fill() and GetData()
methods that can be used to fill and fetch data from the database without implementing a line of
code.
How to use it?
We can use the typed dataset and fill it in the normal way as we do for a non-typed dataset.
Filling Typed Dataset in a usual way

sqlconnection sqlcon = new sqlConnection(//connection string goes here....);


SqlCommand com = new SqlCommand("Select * from Employees", sqlcon);
SqlDataAdapter ada = new SqlDataAdapter(com);
Employees emp = new Employees();
da.Fill(emp,"Employees");

The table name in the fill method should match the table name in the typed dataset.
Using EmployeesTableAdapter:
Filling Typed Dataset using TableAdapter

EmployeesTableAdapters.EmployeesTableAdapter ada = new


EmployeesTableAdapters.EmployeesTableAdapter();
gvEmployees.DataSource = ada.GetData();
gvEmployees.DataBind();

Here, “gvEmployees” is the gridview. In the next sections we will see how to use TableAdapter
and extend the typed dataset to provide custom methods that serve specific purposes. We use the
“customer” table in NorthWind database for this article.
What is a TableAdapter?
TableAdapters provide communication between your application and a database. More specifically,
a TableAdapter connects to a database, executes queries or stored procedures, and either returns a
new data table populated with the returned data or fills an existing DataTable with the returned
data. TableAdapters are also used to send updated data from your application back to the database.
Adding New Functionality
We will try to add a new Selection functionality and a new update functionality using
TableAdapter in Typed dataset using visual studio.

New Select Functionality


You retrieve a particular customer detail by giving the CustomerID.
Right click dataset and click add>Query as shown below.
Figure 6 – Customer Table

This will bring up a new window.


TableAdapter Configuration for Command Type

Select the appropriate option; I have selected “Use SQL statements.”


Clicking Next will bring a window like the one below.
TableAdapter Configuration for Query Type
Select the query type. I have selected the first option: “Select which returns rows.” Click Next and
this will bring up a window to specify the query. Give the parameters with “@” character pre-
pended to it.
TableAdapter Configuration for SQL Statement

I would like to return details of a customer on giving the customerid in this example so I have
given the query:
Select * from Customers where CustomerID = @CustomerID.

Click Finish. We have just added a select functionality to the typed dataset using TableAdapter
writing a single line of code.

New Update Functionality


Repeat the above steps to update the address of the customers. Select “Update” option in step 3,
provide a method name in the next step and give the following query that will update the address,
city, region, postalcode, country, phone and fax by giving the customerid.
The update query will be:
UPDATE [Customers]
SET [Address] = @Address,
[City] = @City,
[Region] = @Region,
[PostalCode] = @PostalCode,
[Country] = @Country,
[Phone] = @Phone,
[Fax] = @Fax
WHERE (([CustomerID] = @Original_CustomerID)).

So our final dataset in designer will look like:


Final Customer table view

How to use the functionality?


To execute the above functionality instantiate the Table adapter.
Instantiating TableAdapter
TestTableAdapters.CustomersTableAdapter ada = new
TestTableAdapters.CustomersTableAdapter();

Now we can see the new select and update functionality with the insert, update and delete method
in TableAdapter intellisense.
Visual studio intellisense for TableAdapter

We can use the above functionality:


Using the new functionality
//Update Address
ada.UpdateAddress("2nd Cross", "Bangalore", "Karnataka", "560061",
"India", "123456789", "!23456789", "100");
//Get details by customerid
grdCustomers.DataSource = ada.GetDataBy("100");
grdCustomers.DataBind();

In the next section we will construct a custom typed dataset using visual studio instead of dragging
and dropping from server explorer.

Constructing Typed Dataset


Add a Typed dataset in Visual Studio as we did above from add new item dialog box. Visual studio
2005 comes with a set of items in the Tool box for constructing the typed dataset. The next sections
will discuss how to use the typed dataset as an alternative to C# custom business objects. Below
shows those items in Visual Studio 2005 Toolbox.
Visual studio Tool bar

1) Drag a Datatable object from the toolbox.


2) To add a column, right click the table object and click Add>Column. Rename the column as you
want.
Add a column

3) To specify datatype, click the properties of the corresponding column and specify it.
So the final typed dataset will look like

Using the constructed Typed Dataset:


Filling this typed dataset can be done in the same way as we did above, keeping in mind that the
database column name and datatype should match with typed dataset. I will explain how to
construct the typed dataset programmatically instead of filling it from the database.
To create a new Products row us the following code.
Create new Prodcuts row
Products.ProductsDataTable prod = new Products.ProductsDataTable();
Products.ProductsRow ProRow = prod.NewProductsRow();
Once we create a typed dataset and compile it, Framework will create all the methods and
properties that will help us in using the typed dataset. The above lines of code
“NewProductsRow()” function is created by the framework which is the equivalent of
“NewRow()” function of the normal datatable.
The following table specifies the usual dataset elements and typed dataset equivalent.
DataSet Element Equivalent Typed DataSet Element
DataTable DatabaseTableNameDataTable
DataTable methods NewDatabaseTableNameRow
AddDatabaseTableNameRow
DeleteDatabaseTableNameRow
DataRowCollection DatabaseTableName
DataRow DatabaseTableNameRow
DataSet Events DatabaseTableNameRowChangeEvent
DatabaseTableNameRowChangeEventHandler
The following code will set the value for the column.
ProRow.ProductName = txtProdName.Text;

Handling Nulls
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.
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:
prod.Rows.Add(ProRow);

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.
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.

Potrebbero piacerti anche