Saturday, 9 February 2013

How to Copy Data from SqlDataSource to Datatable and Operations Using Datatable

Introduction

I wanted to share my experience where the project required with the use of datatables to store data intermediate without moving the data to the database and required to perform some operations. For ex: Selecting some specified rows and computing some arithmetic operations.

Background

Datatable is an object in the ADO.NET Library. Generally, Dataset and Dataview uses the Datatable. Datatable helps in the sorting and Selecting the data present in it by using its methods.

Copying Data From SqlDataSource To Datatable

There is no way to perform direct copy from sqldatasource to datatable. Therefore, we use DataView to copy the data from sqldatasource to datatable.

Sorting Data in Datatable

DataTable.Select() is a method which helps in sorting the data. The select() has 4 overloads. According, to My project requirement i am in need of 2 overloads. It Returns the Array Of the DataRow[] Sorted.

The DataTable.Select() Works exactly as same as the 'where' Clause in SQL. I.e,

1. DataTable.Select("Filter Expression")

DataTable dtr = dt;
DataRow[] uniname = dtr.Select("Name Desc");

2. DataTable.Select("Filter Expression","Sorting Order")

DataTable dtr = dt;
DataRow[] uniname = dtr.Select("City=Bangalore");

Filtering Data in Datatable

DataTable.Compute() is a method which helps in filtering the data. The DataTable.Compute("Required Expression","Filter")