Adding Data to a DataSet
If you use controls like the Windows Forms DataGrid , adding rows to a table is as easy as navigating to the last position in the DataGrid . The DataGrid will insert the row automatically. Unfortunately this approach doesn't work for Web applications; you will need to know the mechanics for inserting new rows. That capability involves creating a blank row with the same schema as the table it will reside in and adding the row to the DataTable , as demonstrated in Listing 11.11.
Listing 11.11 Adding a New Row Programmatically
Private Sub ButtonAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ButtonAdd.Click Dim Row As DataRow = Customers.Tables(0).NewRow() Row("CustomerID") = "HELLO" Row("CompanyName") = "Hello Fudge Company" Row("ContactName") = "Robert Golieb" Row("ContactTitle") = "Fudge Master" Row("Address") = "41 Hershey Street" Row("City") = "Hershey" Row("Region") = "Pennsylvania" Row("Country") = "US" Row("PostalCode") = "06123" Row("Phone") = "606-555-1212" Row("Fax") = "606-555-1213" Customers.Tables(0).Rows.Add(Row) DataGrid1.DataSource = Customers.Tables(0) End Sub
The code in this listing first requests a new blank row. The NewRow method will return a blank row with the same schema as the table it was invoked against. We know the schema of the row, allowing us to use the column indexer to assign values to each column in the row. When finished we need to insert the row into the table's Rows collection. Finally, we need to cause the DataGrid to update. You can reassign the DataSource property as shown in the listing or simply invoke DataGrid.Invalidate .
In our example the same row would be added repeatedly. To create a dynamic insert behavior you need to insert the row and then provide an interface for adding the data. In the case of a DataGrid the grid itself is a suitable control for adding data.
Windows applications are easier than Web applications to build and manage because the graphical user interface is connected to the code in Windows applications. With Web applications the user interface is a rendered Web page; you have to post back to the server to render a new page with the inserted row. However, the basic code for adding rows to a DataSet is the same for both kinds of applications.