Visual Basic: Programmatically add a row to a data bound DataGridView

Platform:Visual Basic
Task:Programmatically add a row to a data bound DataGridView
Discussion:
You need to add a row to a data bound DataGridView. You might be tempted to add a row to the DataGridView, but this won't work if the DataGridView is already bound to a dataset. You need to add the row to the DataTable in the Dataset and then update the tables TableAdapter to refresh the DataGridView.
Example:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim dsNewRow As DataRow
        dsNewRow = SheepMonitoringDataSet.tblSheepGroupPhotos.NewRow
        dsNewRow.Item("SheepGroupID") = 3
        dsNewRow.Item("Filename") = "Skeeter.jpg"
        SheepMonitoringDataSet.tblSheepGroupPhotos.Rows.Add(dsNewRow)
        TblSheepGroupPhotosTableAdapter.Update(SheepMonitoringDataSet)
    End Sub
Back to Index