1 Previous Next 

The fastest way to put one text from a database in a Textbox


This is Tip is meant to show the use of the keyword “Using”, the Try and Catch, the ExecuteScalar and how to concatenate first name and last name to a full name.

To test it you need only a new project with one button and a textbox on a windows form.
And to set your Server name in the connectionstring.

Imports System.Data.SqlClient
'Code for versions starting with VB10SP1 for earlier versions add the Byval's in the method
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgsHandles Button1.Click
        Try
            Using Con As New SqlConnection("Data Source=YourServer;Initial Catalog=Northwind;Integrated Security=True")
                Con.Open()
                Using com As New SqlCommand("Select FirstName + ' ' + Lastname from Employees where EmployeeID = @1", Con)
                    com.Parameters.AddWithValue("@1", 1)
                    Dim textObj = com.ExecuteScalar
                    If Not textObj Is Nothing AndAlso Not textObj Is DBNull.Value Then
                        TextBox1.Text = CStr(textObj)
                    End If
                End Using
            End Using
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class



1 Previous Next