A New Internet Library: Add Your Website/Blog or Suggest A Website/Blog to our Free Web Directory http://anil.myfunda.net.

Its very simple, free and SEO Friendly.
Submit Now....

Thursday, February 7, 2008

All About DATASET

Dataset



When designing data access in your Web application, you have a variety of choices to make about how you communicate with a data source, whether you store data between round trips of the page, and if you do store data, where. The choices you make can determine how efficiently your application runs and how well it scales. There is no one data access strategy that is suitable for all situations. In fact, each choice has its own advantages and disadvantages, which you will need to understand.

The following sections detail the basic design choices you must make for Web Forms data access. The choices are presented here in a sequence; each choice is based on a choice you made previously.

Security NoteAccessing a database from a Web application introduces security issues that you should be aware of. For details, see Access Permissions for Web Applications. For details about accessing SQL Server, see Accessing SQL Server from a Web Application.

Dataset or Direct Access and Data Reader?

A primary choice is whether you want to cache records in a dataset or whether you want to access the database directly and read records using a data reader. For some database operations, such as creating and editing database structures, you cannot use a dataset. For example, if you want to create a new database table from within your application, you cannot do so using a dataset; instead, you would execute a data command. For general data-access scenarios, however, you can often choose between storing records in a disconnected dataset and working directly with the database using data commands.

Note   For details about datasets, see Introduction to Datasets. For details about accessing a database directly, see Introduction to DataCommand Objects in Visual Studio.

Each strategy has inherent advantages that apply to any data access scenario (not just Web Forms pages). For example, datasets make it easier to work with related tables and to work with data from disparate sources. Conversely, using a data reader often results in slightly better performance and memory usage, it eliminates the extra step (and memory requirement) of filling a dataset, and it allows you more direct control over the statements or stored procedures you use. For details about the comparative advantages of each of these approaches in general, see Recommendations for Data Access Strategies.

Datasets and Data Commands in Web Forms Pages

When you are working with Web Forms pages, additional factors come into play when deciding whether to use a dataset or a data reader. A significant factor is the page life cycle — Web Forms pages are initialized, processed, and then discarded with each round trip. If you simply want to display data on the page, then creating a dataset, filling it, and then binding controls to it can represent unnecessary overhead, since the dataset will be discarded immediately. In many cases, it is more efficient to use data reader to fetch the data and then to bind controls to it at run time.

Tip   No matter how you decide to get data from the data source, you should always attempt to minimize the amount of data you use in a page. The more data a query or stored procedure brings back, the more database and server resources you use.

In general, therefore, you might want to assume that in Web Forms pages it is usually better to use data commands to execute SQL statement or stored procedures, using a data reader to fetch data. For example, to display information in a DataList command, you can execute a SQL statement and then bind the control to a data reader. Exceptions to this general rule might be the following:

  • Working with related tables   Datasets allow you to maintain multiple related tables and include support for relations and referential integrity. Working with related records — for example, reading parent and corresponding child records — can be substantially simpler in a dataset than fetching records independently using when executing commands against a database.

  • Exchanging data with other processes   If your Web Forms page is getting its data from another component, such as an XML Web service, you will almost always use a dataset to hold the local copy of the data. Datasets automatically read and write the XML stream used to communicate between components in the .NET Framework.

  • Working with a static set of records   If you need to use the same set of records repeatedly — for example, when users are paging in a grid — it can be efficient to fill those records into a dataset rather than return to the data source with each round trip. This is particularly true if you want to set aside a particular set of records to work with from a database that is changing frequently.

A more general advantage of using a dataset is that it is easier to program than working directly with data commands. However, you must weigh this advantage carefully against other application requirements.

For details about using data commands, see Introduction to DataCommand Objects in Visual Studio.

Save Dataset or Recreate Each Time?

If you do use a dataset, your next choice is whether you want to recreate it with each round trip. You have two options:

  • Each time the page is processed, create an instance of the dataset and fill it. When page processing is finished and the page is sent to the browser, the dataset is discarded.

  • Create and fill the dataset once (typically, the first time the page runs). Then save the dataset in a way that you can retrieve it with each subsequent round trip.

Creating the dataset each time means that with each round trip — effectively, each time the user clicks a button on your page — you execute a query or stored procedure against the data source. For example, you might have a Web Forms page where the user wants to page through data. If you create the dataset each time, the Web Forms page executes a query against the data source to get the next set of records to display.

Tip   Remember to always minimize data transfer. Whenever practical, use selection criteria to reduce the number of records you need on a page.

If you save and restore the dataset, on the other hand, you do not need to go back to the source just to get a few more records. However, saving the dataset has a number of drawbacks. An important one is that the dataset consumes memory between round trips. If the dataset is very large, for example, it can take considerable server memory to store it. If multiple users create large datasets, you can quickly consume available server memory. (An option is to store data in the page; for details, see the next section.)

Another potential drawback is that the dataset can get out of sync with the data source, since you are not refreshing the dataset each time the user clicks a button. If you are working with very volatile data (inventory data, for instance), you might find it better for your application to recreate the dataset with each round trip.

Cache on the Server or on the Client?

If you decide to save a dataset between round trips, you must decide where to keep it. This issue is the standard one of state maintenance in Web Forms pages — where do you store information you want to preserve between round trips? For information about saving values, see Web Forms State Management.

You have two options:

  • On the server, save the dataset in Session state, Application state, or using a cache.

  • On the client — that is, in the page — save the dataset using view state or by putting the data into your own hidden field. (View state is also implemented using a hidden field.)

Storing the dataset on the server uses server resources. If you store too much data (a large dataset, or many users storing small datasets), it can affect server performance and scalability. Using a cache can partly offset this problem, because the cache manager will discard the dataset if the server needs memory or if cached data expires. But because the dataset is not guaranteed to be in the cache, you must add logic to your page to check that the dataset is available in the cache; if not, you must recreate it and put a copy back in the cache.

Storing data in the page means that you do not need server resources to save the data. However, the data becomes part of the HTML stream of the page. If the dataset is large, it can substantially affect the time it takes for the page to load into the user's browser and to post the page back to the server. For details about saving data in view state, see Saving Web Forms Page Values using View State.

Tip   Always try to keep the size of a dataset to a minimum by filling it with only the records you need.

No matter where you decide to store the dataset, you must add logic to your page to save it and restore it at the appropriate time. The following example shows a typical way to store and restore a dataset in Session state. The dataset dsCustomers1 is an instance of the dataset class dsCustomers. Note that the dataset is stored in Session state as type Object. When restoring the dataset from Session state, you must cast it from Object back to a dataset class.

'Visual Basic

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

If Page.IsPostBack Then

dsCustomers1 = CType(Session("myDsCustomers"), dsCustomers)

Else

If Session("myDsCustomers") Is Nothing Then

OleDbDataAdapter1.Fill(dsCustomers1)

Session("myDsCustomers") = dsCustomers1

End If

End If

End Sub


//C#

private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

if (Page.IsPostBack)

{

dsCustomers1 = (dsCustomers) Session["myDsCustomers"];

}

else

{

if (Session["myDsCustomers"] == null)

{

oleDbDataAdapter1.Fill(dsCustomers1);

Session["myDsCustomers"] = dsCustomers1;

}

}

}



Dataset Class




Represents an in-memory cache of data.

For a list of all members of this type, see DataSet Members.

System.Object
   System.ComponentModel.MarshalByValueComponent
      System.Data.DataSet

[Visual Basic]

<Serializable>

Public Class DataSet

Inherits MarshalByValueComponent

Implements IListSource, ISupportInitialize, ISerializable

[C#]

[Serializable]

public class DataSet : MarshalByValueComponent, IListSource,

ISupportInitialize, ISerializable

[C++]

[Serializable]

public __gc class DataSet : public MarshalByValueComponent,

IListSource, ISupportInitialize, ISerializable

[JScript]

public

Serializable

class DataSet extends MarshalByValueComponent implements

IListSource, ISupportInitialize, ISerializable

Thread Safety

This type is safe for multithreaded read operations. You must synchronize any write operations.

Remarks

The DataSet, which is an in-memory cache of data retrieved from a data source, is a major component of the ADO.NET architecture. The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects. For further details about working with DataSet objects, see Creating and Using DataSets.

While DataTable objects contain the data, the DataRelationCollection allows you to navigate though the table hierarchy. The tables are contained in a DataTableCollection accessed through the Tables property. When accessing DataTable objects, note that they are conditionally case-sensitive. For example, if one DataTable is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case-sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case-insensitive. For more information about working with DataTable objects, see Creating a DataTable.

A DataSet can read and write data and schema as XML documents. The data and schema can then be transported across HTTP and used by any application, on any platform that is XML-enabled. You can save the schema as an XML schema with the WriteXmlSchema method, and both schema and data can be saved using the WriteXml method. To read an XML document that includes both schema and data, use the ReadXml method.

In a typical multiple-tier implementation, the steps for creating and refreshing a DataSet, and in turn, updating the original data are to:

  1. Build and fill each DataTable in a DataSet with data from a data source using a DataAdapter.

  2. Change the data in individual DataTable objects by adding, updating, or deleting DataRow objects.

  3. Invoke the GetChanges method to create a second DataSet that features only the changes to the data.

  4. Call the Update method of the DataAdapter, passing the second DataSet as an argument.

  5. Invoke the Merge method to merge the changes from the second DataSet into the first.

  6. Invoke the AcceptChanges on the DataSet. Alternatively, invoke RejectChanges to cancel the changes.

Note   The DataSet and DataTable objects inherit from MarshalByValueComponent, and support the ISerializable interface for remoting. These are the only ADO.NET objects that can be remoted.

Example

[Visual Basic, C#, C++] The following example consists of several methods that, combined, create and fill a DataSet from the Northwind database installed as a sample database with SQLServer 7.0.

[Visual Basic]

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Drawing

Imports System.ComponentModel

Imports System.Windows.Forms


public class DataGridSample

Inherits Form

Private ds As DataSet

Private myGrid As DataGrid


Shared Sub Main

Application.Run(new DataGridSample())

End Sub


public Sub New()

InitializeComponent()

End Sub


public Sub InitializeComponent()

Me.ClientSize = new Size(550, 450)

myGrid = new DataGrid()

myGrid.Location = new Point (10,10)

myGrid.Size = new Size(500, 400)

myGrid.CaptionText = "Microsoft .NET DataGrid"

Me.Controls.Add(myGrid)

Me.Text = "Visual Basic Grid Example"

ConnectToData()

myGrid.SetDataBinding(ds, "Suppliers")

End Sub


Private Sub ConnectToData()

' Create the ConnectionString and create a SqlConnection.

' Change the data source value to the name of your computer.

Dim cString As string = "Persist Security Info=False;Integrated Security=SSPI;database=northwind;server=mySQLServer"

Dim cnNorthwind As SqlConnection = new SqlConnection(cString)

' Create a SqlDataAdapter for the Suppliers table.

Dim adpSuppliers As SqlDataAdapter = new SqlDataAdapter()

' A table mapping tells the adapter what to call the table.

adpSuppliers.TableMappings.Add("Table", "Suppliers")

cnNorthwind.Open()

Dim cmdSuppliers As SqlCommand = _

new SqlCommand("SELECT * FROM Suppliers", cnNorthwind)

cmdSuppliers.CommandType = CommandType.Text


adpSuppliers.SelectCommand = cmdSuppliers

Console.WriteLine("The connection is open.")

ds = New DataSet("Customers")

adpSuppliers.Fill(ds)

' Create a second SqlDataAdapter and SqlCommand to get

' the Products table, a child table of Suppliers.

Dim adpProducts As SqlDataAdapter = new SqlDataAdapter()

adpProducts.TableMappings.Add("Table", "Products")

Dim cmdProducts As SqlCommand = _

new SqlCommand("SELECT * FROM Products", cnNorthwind)

adpProducts.SelectCommand = cmdProducts

adpProducts.Fill(ds)

cnNorthwind.Close()

Console.WriteLine("The connection is closed.")

' You must create a DataRelation to link the two tables.

Dim dr As DataRelation

Dim dc1 As DataColumn

Dim dc2 As DataColumn

' Get the parent and child columns of the two tables.

dc1 = ds.Tables("Suppliers").Columns("SupplierID")

dc2 = ds.Tables("Products").Columns("SupplierID")

dr = new System.Data.DataRelation("suppliers2products", dc1, dc2)

ds.Relations.Add(dr)

End Sub

End Class


[C#]

using System;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Windows.Forms;


public class DataGridSample:Form{

DataSet ds;

DataGrid myGrid;


static void Main(){

Application.Run(new DataGridSample());

}


public DataGridSample(){

InitializeComponent();

}


void InitializeComponent(){

this.ClientSize = new System.Drawing.Size(550, 450);

myGrid = new DataGrid();

myGrid.Location = new Point (10,10);

myGrid.Size = new Size(500, 400);

myGrid.CaptionText = "Microsoft .NET DataGrid";

this.Text = "C# Grid Example";

this.Controls.Add(myGrid);

ConnectToData();

myGrid.SetDataBinding(ds, "Suppliers");

}

void ConnectToData(){

// Create the ConnectionString and create a SqlConnection.

// Change the data source value to the name of your computer.

string cString = "Persist Security Info=False;Integrated Security=SSPI;database=northwind;server=mySQLServer";

SqlConnection myConnection = new SqlConnection(cString);

// Create a SqlDataAdapter.

SqlDataAdapter myAdapter = new SqlDataAdapter();

myAdapter.TableMappings.Add("Table", "Suppliers");

myConnection.Open();

SqlCommand myCommand = new SqlCommand("SELECT * FROM Suppliers",

myConnection);

myCommand.CommandType = CommandType.Text;

myAdapter.SelectCommand = myCommand;

Console.WriteLine("The connection is open");

ds = new DataSet("Customers");

myAdapter.Fill(ds);

// Create a second Adapter and Command.

SqlDataAdapter adpProducts = new SqlDataAdapter();

adpProducts.TableMappings.Add("Table", "Products");

SqlCommand cmdProducts = new SqlCommand("SELECT * FROM Products",

myConnection);

adpProducts.SelectCommand = cmdProducts;

adpProducts.Fill(ds);

myConnection.Close();

Console.WriteLine("The connection is closed.");

System.Data.DataRelation dr;

System.Data.DataColumn dc1;

System.Data.DataColumn dc2;

// Get the parent and child columns of the two tables.

dc1 = ds.Tables["Suppliers"].Columns["SupplierID"];

dc2 = ds.Tables["Products"].Columns["SupplierID"];

dr = new System.Data.DataRelation("suppliers2products", dc1, dc2);

ds.Relations.Add(dr);

}

}





Data table class


DataTable Class

Represents one table of in-memory data.

For a list of all members of this type, see DataTable Members.

System.Object
   System.ComponentModel.MarshalByValueComponent
      System.Data.DataTable

[Visual Basic]

<Serializable>

Public Class DataTable

Inherits MarshalByValueComponent

Implements IListSource, ISupportInitialize, ISerializable

[C#]

[Serializable]

public class DataTable : MarshalByValueComponent, IListSource,

ISupportInitialize, ISerializable

[C++]

[Serializable]

public __gc class DataTable : public MarshalByValueComponent,

IListSource, ISupportInitialize, ISerializable

[JScript]

public

Serializable

class DataTable extends MarshalByValueComponent implements

IListSource, ISupportInitialize, ISerializable

Thread Safety

This type is safe for multithreaded read operations. You must synchronize any write operations.

Remarks

The DataTable is a central object in the ADO.NET library. Other objects that use the DataTable include the DataSet and the DataView.

When accessing DataTable objects, note that they are conditionally case-sensitive. For example, if one DataTable is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case-sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case-insensitive. For more information about working with DataTable objects, see Creating a DataTable.

If you are creating a DataTable programmatically, you must first define its schema by adding DataColumn objects to the DataColumnCollection (accessed through the Columns property). For more information about adding DataColumn objects, see Adding Columns to a Table.

To add rows to a DataTable, you must first use the NewRow method to return a new DataRow object. The NewRow method returns a row with the schema of the DataTable, as it is defined by the table's DataColumnCollection. The maximum number of rows that a DataTable can store is 16,777,216. For more information, see Adding Data to a Table.

The schema of a table is defined by the DataColumnCollection, the collection of DataColumn objects. The DataColumnCollection is accessed through the Columns property. See DataColumn and DataColumnCollection for more information about defining a schema for the table.

The DataTable contains a collection of Constraint objects that can be used to ensure the integrity of the data. For more information, see Adding Constraints to a Table.

To determine when changes are made to a table, use one of the following events: RowChanged, RowChanging, RowDeleting, and RowDeleted. For more information, see Working with DataTable Events.

When an instance of DataTable is created, some of the read/write properties are set to initial values. For a list of these values, see the DataTable constructor.

Note   The DataSet and DataTable objects inherit from MarshalByValueComponent, and support the ISerializable interface for remoting. These are the only ADO.NET objects that can be remoted.

Example

[Visual Basic, C#, C++] The following example creates two DataTable objects, one DataRelation object, and adds the new objects to a DataSet. The tables are then displayed in a DataGrid control by invoking the DataGrid.SetDataBinding method.

[Visual Basic]

' Put the next line into the Declarations section.

private myDataSet As DataSet

Private Sub MakeDataTables()

' Run all of the functions.

MakeParentTable()

MakeChildTable()

MakeDataRelation()

BindToDataGrid()

End Sub

Private Sub MakeParentTable()

' Create a new DataTable.

Dim myDataTable As DataTable = new DataTable("ParentTable")

' Declare variables for DataColumn and DataRow objects.

Dim myDataColumn As DataColumn

Dim myDataRow As DataRow

' Create new DataColumn, set DataType, ColumnName and add to DataTable.

myDataColumn = New DataColumn()

myDataColumn.DataType = System.Type.GetType("System.Int32")

myDataColumn.ColumnName = "id"

myDataColumn.ReadOnly = True

myDataColumn.Unique = True

' Add the Column to the DataColumnCollection.

myDataTable.Columns.Add(myDataColumn)

' Create second column.

myDataColumn = New DataColumn()

myDataColumn.DataType = System.Type.GetType("System.String")

myDataColumn.ColumnName = "ParentItem"

myDataColumn.AutoIncrement = False

myDataColumn.Caption = "ParentItem"

myDataColumn.ReadOnly = False

myDataColumn.Unique = False

' Add the column to the table.

myDataTable.Columns.Add(myDataColumn)

' Make the ID column the primary key column.

Dim PrimaryKeyColumns(0) As DataColumn

PrimaryKeyColumns(0)= myDataTable.Columns("id")

myDataTable.PrimaryKey = PrimaryKeyColumns

' Instantiate the DataSet variable.

myDataSet = New DataSet()

' Add the new DataTable to the DataSet.

myDataSet.Tables.Add(myDataTable)

' Create three new DataRow objects and add them to the DataTable

Dim i As Integer

For i = 0 to 2

myDataRow = myDataTable.NewRow()

myDataRow("id") = i

myDataRow("ParentItem") = "ParentItem " + i.ToString()

myDataTable.Rows.Add(myDataRow)

Next i

End Sub

Private Sub MakeChildTable()

' Create a new DataTable.

Dim myDataTable As DataTable = New DataTable("childTable")

Dim myDataColumn As DataColumn

Dim myDataRow As DataRow

' Create first column and add to the DataTable.

myDataColumn = New DataColumn()

myDataColumn.DataType= System.Type.GetType("System.Int32")

myDataColumn.ColumnName = "ChildID"

myDataColumn.AutoIncrement = True

myDataColumn.Caption = "ID"

myDataColumn.ReadOnly = True

myDataColumn.Unique = True

' Add the column to the DataColumnCollection.

myDataTable.Columns.Add(myDataColumn)

' Create second column.

myDataColumn = New DataColumn()

myDataColumn.DataType= System.Type.GetType("System.String")

myDataColumn.ColumnName = "ChildItem"

myDataColumn.AutoIncrement = False

myDataColumn.Caption = "ChildItem"

myDataColumn.ReadOnly = False

myDataColumn.Unique = False

myDataTable.Columns.Add(myDataColumn)

' Create third column.

myDataColumn = New DataColumn()

myDataColumn.DataType= System.Type.GetType("System.Int32")

myDataColumn.ColumnName = "ParentID"

myDataColumn.AutoIncrement = False

myDataColumn.Caption = "ParentID"

myDataColumn.ReadOnly = False

myDataColumn.Unique = False

myDataTable.Columns.Add(myDataColumn)

myDataSet.Tables.Add(myDataTable)

' Create three sets of DataRow objects, five rows each, and add to DataTable.

Dim i As Integer

For i = 0 to 4

myDataRow = myDataTable.NewRow()

myDataRow("childID") = i

myDataRow("ChildItem") = "Item " + i.ToString()

myDataRow("ParentID") = 0

myDataTable.Rows.Add(myDataRow)

Next i

For i = 0 to 4

myDataRow = myDataTable.NewRow()

myDataRow("childID") = i + 5

myDataRow("ChildItem") = "Item " + i.ToString()

myDataRow("ParentID") = 1

myDataTable.Rows.Add(myDataRow)

Next i

For i = 0 to 4

myDataRow = myDataTable.NewRow()

myDataRow("childID") = i + 10

myDataRow("ChildItem") = "Item " + i.ToString()

myDataRow("ParentID") = 2

myDataTable.Rows.Add(myDataRow)

Next i

End Sub

Private Sub MakeDataRelation()

' DataRelation requires two DataColumn (parent and child) and a name.

Dim myDataRelation As DataRelation

Dim parentColumn As DataColumn

Dim childColumn As DataColumn

parentColumn = myDataSet.Tables("ParentTable").Columns("id")

childColumn = myDataSet.Tables("ChildTable").Columns("ParentID")

myDataRelation = new DataRelation("parent2Child", parentColumn, childColumn)

myDataSet.Tables("ChildTable").ParentRelations.Add(myDataRelation)

End Sub

Private Sub BindToDataGrid()

' Instruct the DataGrid to bind to the DataSet, with the

' ParentTable as the topmost DataTable.

DataGrid1.SetDataBinding(myDataSet,"ParentTable")

End Sub


[C#]

// Put the next line into the Declarations section.

private System.Data.DataSet myDataSet;

private void MakeDataTables(){

// Run all of the functions.

MakeParentTable();

MakeChildTable();

MakeDataRelation();

BindToDataGrid();

}

private void MakeParentTable(){

// Create a new DataTable.

System.Data.DataTable myDataTable = new DataTable("ParentTable");

// Declare variables for DataColumn and DataRow objects.

DataColumn myDataColumn;

DataRow myDataRow;

// Create new DataColumn, set DataType, ColumnName and add to DataTable.

myDataColumn = new DataColumn();

myDataColumn.DataType = System.Type.GetType("System.Int32");

myDataColumn.ColumnName = "id";

myDataColumn.ReadOnly = true;

myDataColumn.Unique = true;

// Add the Column to the DataColumnCollection.

myDataTable.Columns.Add(myDataColumn);

// Create second column.

myDataColumn = new DataColumn();

myDataColumn.DataType = System.Type.GetType("System.String");

myDataColumn.ColumnName = "ParentItem";

myDataColumn.AutoIncrement = false;

myDataColumn.Caption = "ParentItem";

myDataColumn.ReadOnly = false;

myDataColumn.Unique = false;

// Add the column to the table.

myDataTable.Columns.Add(myDataColumn);

// Make the ID column the primary key column.

DataColumn[] PrimaryKeyColumns = new DataColumn[1];

PrimaryKeyColumns[0] = myDataTable.Columns["id"];

myDataTable.PrimaryKey = PrimaryKeyColumns;

// Instantiate the DataSet variable.

myDataSet = new DataSet();

// Add the new DataTable to the DataSet.

myDataSet.Tables.Add(myDataTable);

// Create three new DataRow objects and add them to the DataTable

for (int i = 0; i<= 2; i++){

myDataRow = myDataTable.NewRow();

myDataRow["id"] = i;

myDataRow["ParentItem"] = "ParentItem " + i;

myDataTable.Rows.Add(myDataRow);

}

}

private void MakeChildTable(){

// Create a new DataTable.

DataTable myDataTable = new DataTable("childTable");

DataColumn myDataColumn;

DataRow myDataRow;

// Create first column and add to the DataTable.

myDataColumn = new DataColumn();

myDataColumn.DataType= System.Type.GetType("System.Int32");

myDataColumn.ColumnName = "ChildID";

myDataColumn.AutoIncrement = true;

myDataColumn.Caption = "ID";

myDataColumn.ReadOnly = true;

myDataColumn.Unique = true;

// Add the column to the DataColumnCollection.

myDataTable.Columns.Add(myDataColumn);

// Create second column.

myDataColumn = new DataColumn();

myDataColumn.DataType= System.Type.GetType("System.String");

myDataColumn.ColumnName = "ChildItem";

myDataColumn.AutoIncrement = false;

myDataColumn.Caption = "ChildItem";

myDataColumn.ReadOnly = false;

myDataColumn.Unique = false;

myDataTable.Columns.Add(myDataColumn);

// Create third column.

myDataColumn = new DataColumn();

myDataColumn.DataType= System.Type.GetType("System.Int32");

myDataColumn.ColumnName = "ParentID";

myDataColumn.AutoIncrement = false;

myDataColumn.Caption = "ParentID";

myDataColumn.ReadOnly = false;

myDataColumn.Unique = false;

myDataTable.Columns.Add(myDataColumn);

myDataSet.Tables.Add(myDataTable);

// Create three sets of DataRow objects, five rows each, and add to DataTable.

for(int i = 0; i <= 4; i ++){

myDataRow = myDataTable.NewRow();

myDataRow["childID"] = i;

myDataRow["ChildItem"] = "Item " + i;

myDataRow["ParentID"] = 0 ;

myDataTable.Rows.Add(myDataRow);

}

for(int i = 0; i <= 4; i ++){

myDataRow = myDataTable.NewRow();

myDataRow["childID"] = i + 5;

myDataRow["ChildItem"] = "Item " + i;

myDataRow["ParentID"] = 1 ;

myDataTable.Rows.Add(myDataRow);

}

for(int i = 0; i <= 4; i ++){

myDataRow = myDataTable.NewRow();

myDataRow["childID"] = i + 10;

myDataRow["ChildItem"] = "Item " + i;

myDataRow["ParentID"] = 2 ;

myDataTable.Rows.Add(myDataRow);

}

}

private void MakeDataRelation(){

// DataRelation requires two DataColumn (parent and child) and a name.

DataRelation myDataRelation;

DataColumn parentColumn;

DataColumn childColumn;

parentColumn = myDataSet.Tables["ParentTable"].Columns["id"];

childColumn = myDataSet.Tables["ChildTable"].Columns["ParentID"];

myDataRelation = new DataRelation("parent2Child", parentColumn, childColumn);

myDataSet.Tables["ChildTable"].ParentRelations.Add(myDataRelation);

}

private void BindToDataGrid(){

// Instruct the DataGrid to bind to the DataSet, with the

// ParentTable as the topmost DataTable.

dataGrid1.SetDataBinding(myDataSet,"ParentTable");

}





No comments:

Post a Comment

Post your comments here:

Dotnet-Interviews