To answer your question as asked, you would do this:
For Each row In DataGridView1.Rows.
Cast(Of DataGridViewRow)().
Where(Function(dgvr) Not dgvr.IsNewRow)
'...
Next
I would strongly recommend against that though. You would do better to create a DataTable
and bind that to the grid, then save all the changes in a batch with a data adapter. You might construct the DataTable
manually, e.g.
Private table As DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With Me.table.Columns
.Add("ID", GetType(Integer))
.Add("Name", GetType(String))
End With
Me.DataGridView1.DataSource = Me.table
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using connection As New SqlConnection("connection string here"),
command As New SqlCommand("INSERT INTO MyTable (ID, Name) VALUES (@ID, @Name)", connection),
adapter As New SqlDataAdapter With {.InsertCommand = command}
'...
adapter.Update(Me.table)
End Using
End Sub
Alternatively, you can use the data adapter to construct the table, e.g.
Private table As DataTable
Private adapter As SqlDataAdapter
Private builder As SqlCommandBuilder
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.table = New DataTable
Me.adapter = New SqlDataAdapter("SELECT * FROM MyTable", "connection string here") With {.MissingSchemaAction = MissingSchemaAction.AddWithKey}
Me.builder = New SqlCommandBuilder(Me.adapter)
Me.adapter.FillSchema(Me.table, SchemaType.Source)
Me.DataGridView1.DataSource = Me.table
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.adapter.Update(Me.table)
End Sub
That example uses a command builder but you can also build the InsertCommand
yourself if you want to.