Try something like this:
Using sqlconn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Databases\" + ComboBox1.Text + ".mdf;Integrated Security=True")
Using da As New SqlDataAdapter(String.Empty, sqlconn)
Dim sql As New StringBuilder("SELECT * FROM [")
sql.Append(TreeView1.SelectedNode.Text.Replace("]", "\]"))
sql.Append("] WHERE 1 = 1 ")
If Not String.IsNullOrEmpty(TextBox3.Text) Then
sql.Append("And Gender = @Gender")
da.SelectCommand.Parameters.AddWithValue("@Gender", TextBox3.Text)
End If
Dim startYear As Integer, endYear As Integer
If Integer.TryParse(TextBox1.Text, startYear) AndAlso Integer.TryParse(TextBox2.Text, endYear) Then
sql.Append("And [Year of employment] Between @StartYear And @EndYear")
da.SelectCommand.Parameters.AddWithValue("@StartYear", startYear)
da.SelectCommand.Parameters.AddWithValue("@EndYear", endYear)
End If
da.SelectCommand.CommandText = sql.ToString()
Dim dt As New DataTable()
da.Fill(dt)
DataGridView1.DataSource = dt
End Using
End Using
- Use parameters to fix the SQL Injection vulnerability;
NB: Depending on where they come from, you may still need to validate the ComboBox1.Text
and TreeView1.SelectedNode.Text
values. - Wrap disposable objects in
Using
blocks; - Use
|DataDirectory|
in the connection string to refer to the current application path;
Working with local databases – Smart Client Data[^] - Use
Integer.TryParse
to validate that TextBox1
and TextBox2
contain valid integers; - Remove unused variables;
Now, do yourself a favour and give your controls meaningful names, rather than accepting the default names provided by the designer. You might remember what
ListBox42
represents
now, but when you come back to look at your code in six months time, you won't have a clue! :)
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]