Jump to content

Recommended Posts

Posted

Boas pessoal 😉

O meu pai tem-me andado a chatear a cabeça para fazer uma coisa para ele anotar os gastos que faz mensalmente, tinha pensado em fazer em excel, mas como ando num curso de programação e já percebo um bocado de vb tentei fazer uma coisa mais elaborada e estou com uns problemazitos.

Bem criei uma base de dados chamada despesas, com os seguintes campos: Meses, Agua, Luz, Gas, Zon, Compras, Total. Ao passar para o vb pus o campo "Meses" como combobox, o resto em textbox.

O que acontece e que quando seleciono um mes e coloco os dados, os dados sao gravados nos meses todos, e depois ao fazer update dos dados dá-me erro na sintax da query, ja verifiquei e parece-me certo, mas vou por aqui o codigo todo do programa

Imports System.Data.OleDb
Public Class Form1

    Public Function verificacampos()
        If txtagua.Text.Trim = "" Then
            MsgBox("Introduza o que gastou na água", MsgBoxStyle.Information, "Aviso:")
            Return False
        End If
        If txtluz.Text.Trim = "" Then
            MsgBox("Introduza o que gastou na luz", MsgBoxStyle.Information, "Aviso:")
            Return False
        End If
        If txtzon.Text.Trim = "" Then
            MsgBox("Introduza o que gastou na zon", MsgBoxStyle.Information, "Aviso:")
            Return False
        End If
        If txtgas.Text.Trim = "" Then
            MsgBox("Introduza o que gastou no gas", MsgBoxStyle.Information, "Aviso:")
            Return False
        End If
        If txtcompras.Text.Trim = "" Then
            MsgBox("Introduza o que gastou nas compras", MsgBoxStyle.Information, "Aviso:")
            Return False
        End If
        Return True
    End Function

    Public Function apagarcampos()
        txtagua.Text = ""
        txtcompras.Text = ""
        txtgas.Text = ""
        txtluz.Text = ""
        txtzon.Text = ""
        txttotal.Text = ""
        Return True
    End Function


    Private Sub DespesasBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Validate()
        Me.DespesasBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DespesasDataSet)

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        pnlmes.Enabled = True
        pnlinfo.Enabled = False
        cmdalterar.Enabled = False
        cmdinserir.Enabled = False
    End Sub

    Private Sub MesesComboBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MesesComboBox.SelectedIndexChanged
        pnlmes.Enabled = False
        pnlinfo.Enabled = True
        Dim conexao As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\despesas.accdb")
        Dim query As String = "SELECT * FROM despesas"
        Dim comando As New OleDbCommand(query, conexao)
        conexao.Open()
        Dim registo As OleDbDataReader = comando.ExecuteReader()
        If registo.HasRows Then
            cmdalterar.Enabled = True
            Me.DespesasTableAdapter.Fill(Me.DespesasDataSet.despesas)
        Else
            cmdinserir.Enabled = True
        End If
        conexao.Close()
    End Sub

    Private Sub cmdinserir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdinserir.Click
        If verificacampos() = False Then
            Exit Sub
        End If
        txttotal.Text = Val(txtagua.Text) + Val(txtluz.Text) + Val(txtzon.Text) + Val(txtgas.Text) + Val(txtcompras.Text)
        Dim conexao As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\despesas.accdb")
        Dim query As String = "INSERT INTO despesas ([Meses], [Agua], [Luz], [Zon], [Gás], [Compras], [Total]) VALUES (@Meses, @Agua, @Luz, @Zon, @Gas, @Compras, @Total) "
        Dim comando As New OleDbCommand(query, conexao)
        comando.Parameters.Add("@Meses", OleDbType.VarChar).Value = MesesComboBox.SelectedText
        comando.Parameters.Add("@Agua", OleDbType.VarChar).Value = txtagua.Text
        comando.Parameters.Add("@Luz", OleDbType.VarChar).Value = txtluz.Text
        comando.Parameters.Add("@Zon", OleDbType.VarChar).Value = txtzon.Text
        comando.Parameters.Add("@Gas", OleDbType.VarChar).Value = txtgas.Text
        comando.Parameters.Add("@Compras", OleDbType.VarChar).Value = txtcompras.Text
        comando.Parameters.Add("@Total", OleDbType.VarChar).Value = txttotal.Text
        conexao.Open()
        Dim x As Integer = comando.ExecuteNonQuery()
        If x < 1 Then
            MsgBox("Erro ao inserir dados", MsgBoxStyle.Information, "Aviso:")
        Else
            MsgBox("Dados introduzidos com sucesso", MsgBoxStyle.Information, "Aviso:")
        End If
        conexao.Close()
        comando = Nothing
        pnlmes.Enabled = True
        pnlinfo.Enabled = False
        cmdalterar.Enabled = False
        cmdinserir.Enabled = False
    End Sub

    Private Sub cmdapagar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdapagar.Click
        apagarcampos()
    End Sub

    Private Sub cmdalterar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdalterar.Click
        If verificacampos() = False Then
            Exit Sub
        End If
        txttotal.Text = Val(txtagua.Text) + Val(txtluz.Text) + Val(txtzon.Text) + Val(txtgas.Text) + Val(txtcompras.Text)
        Dim conexao As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\despesas.accdb")
        Dim query As String = "UPDATE despesas SET ([Meses] = @Meses, [Agua] = @Agua, [Luz] = @Luz, [Zon] = @Zon, [Gás] = @Gas, [Compras] = @Compras, [Total] = @Total) WHERE [Meses] = @Meses"
        Dim comando As New OleDbCommand(query, conexao)
        comando.Parameters.Add("@Meses", OleDbType.VarChar).Value = MesesComboBox.SelectedText
        comando.Parameters.Add("@Agua", OleDbType.VarChar).Value = txtagua.Text
        comando.Parameters.Add("@Luz", OleDbType.VarChar).Value = txtluz.Text
        comando.Parameters.Add("@Zon", OleDbType.VarChar).Value = txtzon.Text
        comando.Parameters.Add("@Gas", OleDbType.VarChar).Value = txtgas.Text
        comando.Parameters.Add("@Compras", OleDbType.VarChar).Value = txtcompras.Text
        comando.Parameters.Add("@Total", OleDbType.VarChar).Value = txttotal.Text
        conexao.Open()
        Dim x As Integer = comando.ExecuteNonQuery()
        If x < 1 Then
            MsgBox("Erro ao actualizar dados", MsgBoxStyle.Information, "Aviso:")
        Else
            MsgBox("Dados actualizados com sucesso", MsgBoxStyle.Information, "Aviso:")
        End If
        conexao.Close()
        comando = Nothing
        pnlmes.Enabled = True
        pnlinfo.Enabled = False
        cmdalterar.Enabled = False
        cmdinserir.Enabled = False
    End Sub
End Class
  • Replies 40
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Posted

Mas dá-te erro mesmo, ou o código vai para a:

If x < 1 Then

            MsgBox("Erro ao actualizar dados", MsgBoxStyle.Information, "Aviso:")

        Else

            MsgBox("Dados actualizados com sucesso", MsgBoxStyle.Information, "Aviso:")

        End If

E vai para o x<1?

Se parar no x<1 é porque o valor que estás a ir buscar da combobox não está certo e ao colocar no filtro da query não encontra nada, porque parece que a query está bem...

Oracle Certified Professional - AdministraçãoOracle Certified Professional - Pl/sqlMCPD - Microsoft Certified Professional DeveloperMCTS - Microsoft Certified Technology Specialist

Posted

Troca isto

Dim query As String = "UPDATE despesas SET ([Meses] = @Meses, [Agua] = @Agua, [Luz] = @Luz, [Zon] = @Zon, [Gás] = @Gas, [Compras] = @Compras, [Total] = @Total) WHERE [Meses] = @Meses"

por isto

Dim query As String = "UPDATE [despesas] SET [Meses] = @Meses, [Agua] = @Agua, [Luz] = @Luz, [Zon] = @Zon, [Gás] = @Gas, [Compras] = @Compras, [Total] = @Total WHERE [Meses] = @Meses"

Pedro Martins

Não respondo a duvidas por PM

Posted

Viste o link que aí te coloquei? Tens a certeza que é na query UPDATE e não noutro lado?

Experimenta só com um campo:

Dim query As String = "UPDATE despesas SET [Agua] = @Agua WHERE Meses = @Meses"
Dim comando As New OleDbCommand(query, conexao)
comando.Parameters.Add("@Agua", OleDbType.VarChar).Value = txtagua.Text
comando.Parameters.Add("@Meses", OleDbType.VarChar).Value = MesesComboBox.SelectedText
conexao.Open()
        Dim x As Integer = comando.ExecuteNonQuery()
        If x < 1 Then
            MsgBox("Erro ao actualizar dados", MsgBoxStyle.Information, "Aviso:")
        Else
            MsgBox("Dados actualizados com sucesso", MsgBoxStyle.Information, "Aviso:")
        End If
        conexao.Close()

Se continuar a dar erro ainda assim, o problema pode vir da linha de código:

MesesComboBox.SelectedText

Coloca antes:

MesesComboBox.Text
Posted

substitui por isto

Dim query As String = "UPDATE despesas SET  [Agua] = @Agua, [Luz] = @Luz, [Zon] = @Zon, [Gás] = @Gas, [Compras] = @Compras, [Total] = @Total WHERE [Meses] = @Meses"

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.