1

I'm trying to generate a query dynamically using textbox values from my Bookings form to update only those values that were entered by the user.

I am using the following code:

Dim str As String

str = "UPDATE Bookings SET "
Dim first As Integer = 1
For Each x As Control In Me.Controls
    If x.GetType Is GetType(TextBox) Then
        If first = 1 Then
            first = 2
        Else
            str &= ","
        End If
        If x.Tag = 1 Then
            str = str & x.Name & " = @" & x.Name
        End If
    End If
Next

But it is generating the query like this:

Update Bookings SET ,,booking_date = @booking_date,,,,,cust_name = @cust_name where bookingID = @bookingID

Or if I want to update just 1 field it generates this:

Update Bookings SET ,,,,,,,cust_name = @cust_name where bookingID = @bookingID
2
  • 1
    I know this does not answer your question at all, but please consider using SQLCommand and SQLParameters if this code is meant for production use. Generating SQL like that is a massive security flaw :) Commented Sep 19, 2011 at 17:35
  • I've used sqlcommand and sql parameters and this code is just to generate a query at run time for textboxes having a value Commented Sep 19, 2011 at 23:07

1 Answer 1

1
Dim str As String  
str = "UPDATE Bookings SET "
Dim comma As string = ""
For Each x As Control In Me.Controls
  If x.GetType Is GetType(TextBox) Then
    If x.Tag = 1 Then
      str &= comma & x.Name & " = @" & x.Name
      comma = ","
    End If
  End If
Next

And here is the One line answer.

Dim str = "UPDATE Bookings SET " & String.Join(",", (From _E In Controls.OfType(Of Control)() Where _E.GetType() Is GetType(TextBox) AndAlso _E.Tag = "1" Select _E.Name).ToList())
Sign up to request clarification or add additional context in comments.

1 Comment

I have 2 masked text boxes 1 is cust_id and its mask is "csc- " i.e. four integer values are required after csc- and the other one is contact whose mask is " - " i.e. four integer values are required before '-' and 7 integer values are required after '-'......But both these textboxes are not getting validated and i have put .tag = 1 at validated event and i have also tried it at textchanged event but useless and the query is not changed for these if some value is entered in these 2 textboxes...Please suggest a remedy for this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.