add lines to datagridview

Asked

Viewed 30 times

1

How can I declare @NIF as a string

Dim sqlConString As String = "Server=localhost\TESTE;Database=tempTest;User Id=sa;Password=123"
    Dim conn = New SqlConnection(sqlConString)
    Try
        Conn.Open()
        Dim strSQL As String = "SELECT * From Computador Where Nifcliente = @NIF"
        conn.Close()
        Dim da As New SqlDataAdapter(strSQL, Conn)
        Dim ds As New DataSet
        da.Fill(ds, "Computador")
        DataGrid.DataSource = ds.Tables(0)
    Catch ex As SqlException
        MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
    End Try
  • As it is a single value it would not be simpler to do so: "SELECT * From Computador Where Nifcliente = '" + nif + "'", being nif the variable string with the value?

2 answers

0


Dim sqlConString As String = "Server=localhost\TESTE;Database=tempTest;User Id=sa;Password=123"
    Dim conn = New SqlConnection(sqlConString)
    Try
        conn.Open()
        Dim strSQL As String = "SELECT * From Computador Where Nifcliente = '" + clientNIF + "'"
        conn.Close()
        Dim da As New SqlDataAdapter(strSQL, conn)
        Dim ds As New DataSet
        da.Fill(ds, "Computador")
        DataGrid.DataSource = ds.Tables(0)
    Catch ex As SqlException
        MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
    End Try

0

You can do the following:

Dim strSQL As String = string.format("SELECT * From Computador Where Nifcliente = {0)",NIF)

Better would be:

        Dim sqlConString As String = "Server=localhost\TESTE;Database=tempTest;User Id=sa;Password=123"
        Dim conn = New SqlConnection(sqlConString)

        Try
            Conn.Open()

            Dim strSQL As String = "SELECT * From Computador Where Nifcliente = @NIF"
            Dim cmd As New SqlClient.SqlCommand(strSQL, Conn)

            cmd.Parameters.Add(New SqlClient.SqlParameter("@NIF", ValorDeNIF))

            Dim da As New SqlDataAdapter(cmd)
            Dim ds As New DataSet

            da.Fill(ds, "Computador")

            conn.Close()

            DataGrid.DataSource = ds.Tables(0)

        Catch ex As SqlException
            MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
        End Try

Browser other questions tagged

You are not signed in. Login or sign up in order to post.