VB.Net - Search String for Character and Add Single Quotes

Good Day Experts!

I have a VB.Net form that takes User input and retrieves records from a SQL database for display in a DataGrid.

I need to allow the User to enter multiple values in on2 of the textboxes.  My plan was to tell the User to enter just a single value or multiples separated by a comma.  I have my query behind the "Get Records" button built to accept
where in ('Value1','Value3'...etc).

I was going to iterate through the string until each comma was encountered then add a starting/ending single quote around the value then put the string back together.  

Question:

Can you think of any functions that may help me achieve this end goal in the simplest fashion?

Thanks,
jimbo99999
Jimbo99999Asked:
Who is Participating?
 
Jacques Bourgeois (James Burger)PresidentCommented:
Dim values As String = "One,Two,Three"
            values = "'" & values.Replace(",", "','") & "'"
0
 
louisfrCommented:
As always when injecting user input into SQL, use a parameterized query.
        Dim csv = "value1,value2,value3"
        Dim values = csv.Split(",")
        Dim cmd = New SqlCommand()
        For i As Integer = 0 To values.Length - 1
            cmd.Parameters.AddWithValue(i.ToString("'@p'0"), values(i))
        Next
        cmd.CommandText = "select ... where in (" + String.Join(",", Enumerable.Range(0, values.Length).Select(Function(i) i.ToString("'@p'0"))) + ");"

Open in new window

0
 
Jimbo99999Author Commented:
Thanks for your responses.  I am working on the project this evening.

jimbo99999
0
 
Jimbo99999Author Commented:
Thanks James...I did not go down that path of thought process to achieve the end goal.  It is working great now.

jimbo99999
0
 
louisfrCommented:
It's working great until someone puts "blabla'); drop table VeryImportantTable; --" in your input string.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.