In the next few sections, you'll see how to create a new DataSet and new DataTable . You'll also see how to manually create the DataTable schema using DataColumns . Finally, you will add some data to the DataSet using the DataRow object.
The first step to working with a DataSet is to create a new instance of a DataSet object. You can do this by using the following code in Visual Basic .NET:
Dim dsCompany as New DataSet()
or like this using C#:
DataSet dsCompany = new DataSet();
When you have a DataSet object, the next step is to add a DataTable . The DataTable contains the columns and rows that make up the data you'll add later. To add a new table to the DataSet , you use the Add() method of the Tables collection in the DataSet object, as in the following line of Visual Basic .NET code:
dim dtEmployees as DataTable = dsCompany.Tables.Add("Employees")
or like this using C#:
DataTable dtEmployees = dsCompany.Tables.Add("Employees");
Notice how the "new" keyword is not used to add a new DataTable to the DataSet . The Add() method of the Tables collection in the DataSet object creates a new DataTable , adds it to the collection of tables inside the DataSet , and then returns the object, automatically.
Now that you have a DataTable , it's time to define exactly what data the table will contain. For this example, the DataTable contains only three columns: EmployeeID, FirstName, and LastName. The EmployeeID is a standard identity field, which will also serve as the primary key. The FirstName and LastName columns will contain strings.
DataColumn s are added to a DataTable in precisely the same way DataTable s are added to DataSet s. In this case, you will not need to refer back to the columns often, so you can just add the columns to the table and ignore the DataColumn objects that are returned from the Add() method. Listing 2.1 adds these three columns to the dtEmployees DataTable in Visual Basic .NET. Listing 2.2 performs the same actions in C#.
dtEmployees.Columns.Add("EmployeeID", Type.GetType("System.Int32")) dtEmployees.Columns.Add("FirstName", Type.GetType("System.String")) dtEmployees.Columns.Add("LastName", Type.GetType("System.String"))
dtEmployees.Columns.Add("EmployeeID", typeof(int)); dtEmployees.Columns.Add("FirstName", typeof(string)); dtEmployees.Columns.Add("LastName", typeof(string));
The second argument of the Add() method in Listings 2.1 and 2.2 expects a data type. The Type.GetType() and typeof() methods return the proper data types that the Add() method wants.
When adding data later in the next few sections, the EmployeeID column should automatically generate a number for each new record added. To achieve this functionality, you must enter one additional line of code:
dtEmployees.Columns(0).AutoIncrement = true;
or in C#:
dtEmployees.Columns.AutoIncrement = true;