|
|
Title | Programmatically add a record to a DataSet bound to a DataGridView in Visual Basic 2005 |
Description | This example shows how to programmatically add a record to a DataSet bound to a DataGridView in Visual Basic 2005. |
Keywords | DataSet, DataGridView, add record, Visual Basic 2005 |
Categories | Database, Controls |
|
|
To build the DataSet at design time:
- Add a DataSet to the form.
- In the Properties window, open the Tables collection and add a table.
- Use the Table editor to add columns to the table.
To bind the DataGridView to the DataSet at design time:
- Add a DataGridView to the form.
- Set its DataSource property to the DataSet.
- Set its DataMember property to the table.
In this example, fill in first and last names and click the Add button. The following code verifies that you entered two names. It then uses the DataTable's NewRow method to create a DataRow of the proper type for the table. It fills in the first and last names, and adds the row to the table's Rows collection.
|
|
Private Sub btnAdd_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnAdd.Click
' Validation.
If txtFirstName.Text.Length = 0 Then
MessageBox.Show("Please enter a First Name", _
"Missing First Name", MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
txtFirstName.Focus()
Exit Sub
End If
If txtLastName.Text.Length = 0 Then
MessageBox.Show("Please enter a Last Name", _
"Missing Last Name", MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
txtLastName.Focus()
Exit Sub
End If
' Get a new record of the correct "shape" for the table.
Dim new_row As DataRow = dsPeople.Tables(0).NewRow()
' Fill in the record's values.
new_row.ItemArray = New Object() {txtFirstName.Text, _
txtLastName.Text}
' Add the record to the table.
dsPeople.Tables(0).Rows.Add(new_row)
txtFirstName.Clear()
txtLastName.Clear()
End Sub
|
|
|
|
|
|