Click here to Skip to main content
14,766,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm doing a project vb.net 2010 and I'm having difficulty creating a update and insert directly into the datagridview without using buttons, this fact should be made through stored procedure, I'm using conection string to connect the sql server database.

-- Update --

are entering only have to press a Tab and Enter to save, I would like to press the enter key at the end of typing to enter


Private Sub DadoUnico_KeyDown (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DadoUnico.KeyDown
         If e.KeyCode = Keys.Enter Then
             SendKeys.Send ("{ENTER}")
             DadoUnico.Enabled = True
              try


             cn.Open ()
             cd = New SqlCommand ("sp_I_Cad_Unioinsere", cn)
             cd.CommandType = Data.CommandType.StoredProcedure
             cd.Parameters.Add ("@ idlog" SqlDbType.VarChar). Value = frmCad_Cadastro.Codigo.Text
             cd.Parameters.AddWithValue ("@ bikelog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("Bike_Log"). Value)
             cd.Parameters.AddWithValue ("@ ModeloLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("Modelo_Log"). Value)
             cd.Parameters.AddWithValue ("@ CorLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("Cor_Log"). Value)
             cd.Parameters.AddWithValue ("@ NumSerieLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("NumSerie_Log"). Value)
             cd.Parameters.AddWithValue ("@ AjuSisRetLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("AjuSisRet_Log"). Value)
             cd.Parameters.AddWithValue ("@ OleoPrefLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("OleoPref_Log"). Value)
             cd.Parameters.AddWithValue ("@ PresPneuLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("PresPneu_Log"). Value)
             cd.Parameters.AddWithValue ("@ AltFreiosLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("AltFreios_Log"). Value)
             cd.Parameters.AddWithValue ("@ PresAmorLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("PresAmor_Log"). Value)
             cd.Parameters.AddWithValue ("@ PresSuspLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("PresSusp_Log"). Value)

             cd.ExecuteNonQuery ()
             MsgBox ("successfully inserted")


         Catch ex As Exception
             MsgBox ("Error:" & Err.Description)
         end Try
         cn.Close ()
         end If

is not giving error, this inserting the insert would like to improve it.
the procedure is correct, why does this by entering only have to press the tab key and enter, to enter. I would only enter precionar last cell in the User type to add.
worked the same as I did. wanted a method that fill the cell to be saved when you press the enter key is another event that could use this in place - KeyDown. RowLeave told me this, but could not because they gave the connection was open.






this code works good, but not for what I need.
but already managed to solve my problem with the code otherwise.
I appreciate the attention.


Posted
Updated 10-Mar-12 8:18am
v7
Comments
Kschuler 7-Mar-12 9:47am
   
What code or setup are you using now, and why is/isn't it working? Are you getting error messages, if so what are they? We need more information to help you.
geice 7-Mar-12 9:57am
   
are entering only have to press a Tab and Enter to save, I would like to press the enter key at the end of typing to enter


Private Sub DadoUnico_KeyDown (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DadoUnico.KeyDown
If e.KeyCode = Keys.Enter Then
SendKeys.Send ("{ENTER}")
DadoUnico.Enabled = True
try


cn.Open ()
cd = New SqlCommand ("sp_I_Cad_Unioinsere", cn)
cd.CommandType = Data.CommandType.StoredProcedure
cd.Parameters.Add ("@ idlog" SqlDbType.VarChar). Value = frmCad_Cadastro.Codigo.Text
cd.Parameters.AddWithValue ("@ bikelog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("Bike_Log"). Value)
cd.Parameters.AddWithValue ("@ ModeloLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("Modelo_Log"). Value)
cd.Parameters.AddWithValue ("@ CorLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("Cor_Log"). Value)
cd.Parameters.AddWithValue ("@ NumSerieLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("NumSerie_Log"). Value)
cd.Parameters.AddWithValue ("@ AjuSisRetLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("AjuSisRet_Log"). Value)
cd.Parameters.AddWithValue ("@ OleoPrefLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("OleoPref_Log"). Value)
cd.Parameters.AddWithValue ("@ PresPneuLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("PresPneu_Log"). Value)
cd.Parameters.AddWithValue ("@ AltFreiosLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("AltFreios_Log"). Value)
cd.Parameters.AddWithValue ("@ PresAmorLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("PresAmor_Log"). Value)
cd.Parameters.AddWithValue ("@ PresSuspLog" frmCad_Cadastro.DadoUnico.CurrentRow.Cells ("PresSusp_Log"). Value)

cd.ExecuteNonQuery ()
MsgBox ("successfully inserted")


Catch ex As Exception
MsgBox ("Error:" & Err.Description)
end Try
cn.Close ()
end If



Kschuler 7-Mar-12 10:02am
   
For future reference, if you have code or more information to add that might help, please click the Improve Question button and add it there instead of in a comment. In your question it can be formatted nicely. I did it for you this time.
Kschuler 7-Mar-12 10:04am
   
Are you getting an error message? What does your stored procedure look like?
geice 10-Mar-12 13:19pm
   
this code works good, but not for what I need.
but already managed to solve my problem with the code otherwise.
I appreciate the attention.

Why do you have this bit of code?
SendKeys.Send ("{ENTER}")


You just checked to see if the user pressed the enter key, and then you basically just press it again, which might just call that whole method again and put you in an infinite loop.

Remove the sendkeys statement and it should work any time the user presses the enter key. If you want it to work for both the enter key and the tab key, you should change your If e.KeyCode statement into a select case statement like this:

Select Case e.KeyCode
    Case Keys.Enter, Keys.Tab
        'Code that calls stored procedure
End Select
   
Comments
geice 8-Mar-12 7:04am
   
yes, this line used for this very thing.
geice 8-Mar-12 7:05am
   
SendKeys.Send ("{ENTER}")
Kschuler 8-Mar-12 9:07am
   
You're using it for what? Your code will already be called when a user hit's the enter key.
geice 9-Mar-12 6:26am
   
this line used for this very thing.
Kschuler 9-Mar-12 9:08am
   
Have you debugged your code? If you put a breakpoint where it says cn.Open() does it EVER get executed?
geice 10-Mar-12 13:34pm
   
this code works good, but not for what I need.
but already managed to solve my problem with the code otherwise.
I appreciate the attention.
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
   
v2
Comments
André Kraak 10-Mar-12 14:01pm
   
Edited solution:
Added pre tags

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900