JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating Data Columns in Code

After creating a table in the DataTableCode example in the previous topic, it's time to create the columns in that table. The columns specify the structure of the table because they specify the type and name of each column; after the table has been so constructed, we can add data-that is, the rows.

I'll add three text string fields to the Employees table in this example: "First Name", "Last Name", and "Phone". I'll also add an Int32 field to hold an ID value. To add a new column, you must specify a type in the column's DataType value. The data types you can use for columns in Visual Basic are System.Boolean, System.Byte, System.Char, System.DateTime, System.Decimal, System.Double, System.Int16, System.Int32, System.Int64, System.SByte, System.Single, and System.String. Here's how I create the new columns:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
    System.EventArgs) Handles Button1.Click
    Dim Table1 As DataTable
    Table1 = New DataTable("Employees")

    Dim FirstName As DataColumn = New DataColumn("First Name")
    FirstName.DataType = System.Type.GetType("System.String")

    Dim LastName As DataColumn = New DataColumn("Last Name")
    LastName.DataType = System.Type.GetType("System.String")

    Dim ID As DataColumn = New DataColumn("ID")
    ID.DataType = System.Type.GetType("System.Int32")

    Dim Phone As DataColumn = New DataColumn("Phone")
    Phone.DataType = System.Type.GetType("System.String")

Now we've added four columns to the Employees table. It's time to start adding some data to this table, and I'll do that in the next topic.

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor