Selecting from a database into a DataGridView I have a piece of code which grabs data from an SQL database and displays it in a DataGridView. This code works perfectly fine for me.

It has been pointed out to me that the below code is bad programming:

Imports System.Data.SqlClient


Public Class Form1

Dim dbConnection As SqlConnection
Dim dbCommand As SqlCommand
Dim dbAdapter As SqlDataAdapter
Dim DataSet As New DataSet
Dim strSQL As String
Dim dbCount As String

Public Sub SQLConnect()
dbConnection = New SqlConnection("Data Source=connectionhere\sqlexpress;Initial Catalog=line_log;Integrated Security=True")
dbConnection.Open()
End Sub

Public Sub SQLCommand()
dbCommand = New SqlCommand(strSQL, dbConnection)
End Sub

Public Sub SQLAdapter()
dbAdapter = New SqlDataAdapter(strSQL, dbConnection)
End Sub

Public Sub SQLDisconnect()
dbConnection.Close()
End Sub

Public Sub DGVLoad()
Try
SQLConnect()
strSQL = "SELECT * FROM [Products]"
SQLAdapter()
DataSet.Clear()
dbAdapter.Fill(DataSet)
SQLDisconnect()
DataGridView1.DataSource = DataSet.Tables(0)

Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DGVLoad()
End Sub


Could someone explain to me why what I am doing is bad practice?
Three possible problems that I see.



dbConnection = New SqlConnection("Data Source=connectionhere\sqlexpress;Initial Catalog=line_log;Integrated Security=True")


You have a hard-coded connection string. If you want a different database location then you need to edit the code. Perhaps it's better to have the connection string in an editable config file.



The original version which prompted this review ...

strSQL = "SELECT [item] FROM [table] WHERE ([item] = 'value')"


... seems to build the select statement by string manipulation of the value and therefore may be vulnerable to SQL injection.



You have SQL code and Form code in the same source file. It may be better to separate these into different classes so that they can be tested and re-used independently.