This code works good, but not for what I need.
However I have managed to solve my problem with the code otherwise.
Public Class frmPrincipal
Dim strConexao As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=" & Environment.CurrentDirectory & "\grid.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim isNovo As Boolean = False
Private Sub frmPrincipal_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
grid1.Columns.Add("colId", "Id")
grid1.Columns.Add("colNome", "Nome")
grid1.Columns.Add("colNumero", "Numero")
grid1.Columns(0).ReadOnly = False
preencherDados(grid1)
End Sub
Public Sub adicionar(nome As String, numero As Integer)
Dim conexao As SqlConnection = New SqlConnection(strConexao)
Dim Comando As SqlCommand = New SqlCommand("INSERT INTO Teste(Nome, Numero) Values ('" & nome & "','" & numero & "')", conexao)
Try
conexao.Open()
Comando.ExecuteNonQuery()
conexao.Close()
Catch ex As SqlException
MsgBox(ex.Message)
End Try
End Sub
Public Sub atualizar(id As Integer, nome As String, numero As Integer)
Dim conexao As SqlConnection = New SqlConnection(strConexao)
Dim Comando As SqlCommand = New SqlCommand("UPDATE Teste Set Nome = '" & nome & "', Numero = '" & numero & "' WHERE id = " & id, conexao)
Try
conexao.Open()
Comando.ExecuteNonQuery()
conexao.Close()
Catch ex As SqlException
MsgBox(ex.Message)
End Try
End Sub
Public Sub preencherDados(grid As DataGridView)
Dim conexao As SqlConnection = New SqlConnection(strConexao)
Dim comando As SqlCommand = New SqlCommand("SELECT * FROM Teste", conexao)
Dim dr As SqlDataReader
Try
conexao.Open()
dr = comando.ExecuteReader
Do While dr.Read
grid1.Rows.Add(dr(0).ToString, dr(1).ToString, dr(2).ToString)
Loop
dr.Close()
conexao.Close()
Catch ex As SqlException
MsgBox(ex.Message)
End Try
End Sub
Private Sub grid1_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles grid1.CellBeginEdit
If grid1.CurrentRow.IsNewRow Then
isNovo = True
End If
End Sub
Private Sub grid1_RowValidated(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grid1.RowValidated
isNovo = False
End Sub
Private Sub grid1_RowValidating(sender As Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles grid1.RowValidating
If grid1.IsCurrentRowDirty Then
grid1.CommitEdit(DataGridViewDataErrorContexts.Commit)
If isNovo = True Then
adicionar(grid1.Rows(e.RowIndex).Cells("colNome").Value, grid1.Rows(e.RowIndex).Cells("colNumero").Value)
Else
atualizar(grid1.Rows(e.RowIndex).Cells("colId").Value, grid1.Rows(e.RowIndex).Cells("colNome").Value, grid1.Rows(e.RowIndex).Cells("colNumero").Value)
End If
End If
End Sub
Public Sub removeRows(grid As DataGridView)
If grid1.Rows.Count > 0 Then
For Each dr As DataGridViewRow In grid.Rows
If Not dr.IsNewRow Then grid.Rows.Remove(dr)
Next
End If
End Sub
End Class