JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating Data Rows in Code

We've created a data table named Employees in the DataTableCode example on the CD-ROM in the previous two topics, and now it's time to stock that table with data, using DataRow objects. I'll add four rows of data to our table here.

To create a DataRow object for insertion in a particular table, you call the table's NewRow method, which returns a DataRow object configured with the columns you've already set up in the table. You can then reach the fields in the row with the Item property. For example, to set the "First Name" field to the value "Ralph", you can use this code: Row1.Item("First Name") = "Ralph". In fact, you can abbreviate this as Row1("First Name") = "Ralph". After you've filled the fields in the row you're working on, you can add it into the table with the table's Rows collection's Add method. Here's how I add the data you see in Figure 22.2 to the Employees table:

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

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

    Row1 = Table1.NewRow()

    Row1("First Name") = "Ralph"
    Row1("Last Name") = "Kramden"
    Row1("ID") = 1
    Row1("Phone") = "(555) 111-2222"


    Row2 = Table1.NewRow()

    Row2("First Name") = "Ed"
    Row2("Last Name") = "Norton"
    Row2("ID") = 2
    Row2("Phone") = "(555) 111-3333"


    Row3 = Table1.NewRow()

    Row3("First Name") = "Alice"
    Row3("Last Name") = "Kramden"
    Row3("ID") = 3
    Row3("Phone") = "(555) 111-2222"

    Row4 = Table1.NewRow()

    Row4("First Name") = "Trixie"
    Row4("Last Name") = "Norton"
    Row4("ID") = 4
    Row4("Phone") = "(555) 111-3333"


    Dim ds As New DataSet()
    ds = New DataSet()
    DataGrid1.SetDataBinding(ds, "Employees")
End Sub

And that's all it takes; note that at the end of the code, I add the new table to a dataset and bind that dataset to the data grid you see in Figure 22.2. In this way, we've created an entire dataset from scratch, no database connection needed.

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor