-3

Image of the error

I am new to Vb.net programing and I need a little help here, I pretend to send info to my database, the first query gives me the id I need and I declare it as "postoid", when I later try to call it (in the insert into part) it says it is not declared, I have googled the problem a hundred times but I couldn't find the answer.

Ps: this code is all in the same private sub

Try
    mysqlconn.Open()
    queryrow = "Select * from postos where postos_nome ='" & TextBox1.Text & "'"
    COMMANDuser1 = New MySqlCommand(queryrow, mysqlconn)
    READERuser = COMMANDuser1.ExecuteReader

    While READERuser.Read
        Dim postoid = READERuser.GetString("postos_id")
    End While

    mysqlconn.Close()

Catch ex As Exception
End Try

Dim sqlquery As String = "INSERT INTO computadores VALUES (0,'" & pcname.ToUpper & "','" & ip & "','" & so & "','" & cpu & "','" & ram & "','" & gc & "','" & wserial & "','" & mnome & "','" & mserial & "','" & "--- ,,'Inativo','" & empresaid & "','" & postoid & "','" & userid & "')"
Dim sqlcommand As New MySqlCommand

With sqlcommand

    .CommandText = sqlquery
    .Connection = mysqlconn
    .ExecuteNonQuery()

End With
MsgBox("Computador Adicionado")
Dispose()
Close()
user3697824
  • 538
  • 4
  • 15
Reuter00
  • 83
  • 1
  • 1
  • 7

1 Answers1

2

Your variable postoid is out-of-scope outside the block it is declared in.

All you need to do is declare it outside the Try structure:

Dim postoid As String = ""

queryrow = "Select postos_id from postos where postos_nome = @PostosNome"

Using COMMANDuser1 As New MySqlCommand(queryrow, mysqlconn)
    COMMANDuser1.Parameters.Add("@PostosNome", TextBox1.Text)

    mysqlconn.Open()
    READERuser = COMMANDuser1.ExecuteReader()

    While READERuser.Read
        postoid = READERuser.GetString("postos_id")
    End While

    mysqlconn.Close()

End Using

If postoid <> "" Then
    ' perform the insert...

I did not actually use Try in that, as you have no code in your Catch block - having no code in the Catch block has the effect of hiding errors. You want to see the errors.

For using SQL parameters, see, e.g., Inserting data into a MySQL table using VB.NET but please use .Add instead of .AddWithValue - the latter will not always work as intended.

Community
  • 1
  • 1
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • Also `ExecuteScalar` would be nicer! – shadow Jan 26 '16 at 11:56
  • @shadow Yes, but there is the messy potential problem of no results being returned: [Execute Scalar to trap error in case of no records returned](http://stackoverflow.com/a/13253718/1115360). – Andrew Morton Jan 26 '16 at 12:04
  • From MSDN `Return Value Type: System.Object The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.` So I don't believe there is a problem. – shadow Jan 26 '16 at 12:11