|
|
Title | Create records that have an AutoNumber field and find out what the newly created field value is in VB .NET |
Description | This example shows how to create records that have an AutoNumber field and find out what the newly created field value is in VB .NET |
Keywords | DataSet, VB.NET, data, database, ADO.NET, AutoNumber, Auto Number, AutoIncrement |
Categories | Database, VB.NET |
|
|
First, create a DataSet and DataAdapters to load the data. See the example Display the data in a DataSet by using as DataGrid control in VB .NET for instructions.
When the program starts, the Form_Load event handler uses the following code to load the data into the DataSet. When the form closes, the Form_Closing event handler saves any changes to the Students data.
|
|
' Load the DataSet.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
daStudents.Fill(dsStudents)
End Sub
' Save the data.
Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
As System.ComponentModel.CancelEventArgs) Handles _
MyBase.Closing
daStudents.Update(dsStudents)
End Sub
|
|
To add a new record to the Students table, the program finds the table's DataTable object on the DataSet. It calls that object's NewRow method to make a new row for the table. It sets values for all of the record's fields except the AutoNumber field StudentID. It then adds the new row to the DataTable's Rows collection. After this, the StudentID field contains the auto-generated value.
|
|
' Add a new Students record.
Private Sub btnMakeStudent_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnMakeStudent.Click
Dim dt_students As DataTable = _
dsStudents.Tables("Students")
Dim new_row As DataRow = dt_students.NewRow()
' Leave StudentID blank because it's an AutoNumber
' field.
new_row.Item("FirstName") = txtFirstName.Text
new_row.Item("LastName") = txtLastName.Text
Try
txtFirstName.Text = ""
txtLastName.Text = ""
dt_students.Rows.Add(new_row)
MessageBox.Show("New StudentID: " & _
new_row.Item("StudentID").ToString())
Catch ex As Exception
MessageBox.Show("Error creating new Student." & _
vbCrLf & ex.Message)
End Try
End Sub
|
|
For more information on database programming in VB .NET, see my book Visual Basic .NET Database Programming.
|
|
|
|
|
|