I have a search form built in ASP.NET that has a dropdown list which determines which table to search from. Both tables have similar structure, but the column names are different in places, so I put each table’s information in a separate table. It’s basically set up like this:
Name|Form Field Name|Table Name|Table Column Name
From there I set up a loop that will hold the form field names, the table name, and the column names depending on the selection made in the dropdown list. The loop will take that information and build an separate MySQL query using StringBuilder based on the user’s input. Here’s the loop:
If drFields.HasRows Then
While drFields.Read()
If drFields("ASPControlName") <> "" Then
If strbQuery.ToString <> "" Then
strbQuery.Append(" AND ")
End If
strbQuery.Append(" " & drFields("DBField") & " LIKE '%" & drFields("ASPControlName").ToString & "%' ")
End If
End While
End If
My issue, as I’m sure you can tell, is that the drFields(“ASPControlName”), which is filled with something along the lines of txtFirstName.Text.Trim, will only come out to a string with txtFirstName.Text.Trim in it. The variable doesn’t translate to referencing the textbox as I want it to.
I know this is probably a backwards way of doing it, but is it even possible to achieve what I’m trying to? Thanks!
Very true. I wouldn’t continue this route.
Yes, you can use reflection to get a hold of the control and invoke the Property you need to in order to receive the actual value but since this is not a good approach at all, I won’t provide an example.
Also, building dynamic queries like you describe, need special handling to make sure that you are not exposing yourself to SQL Injection attacks. Try to rethink the strategy here.
It’s difficult to suggest something that would work for you since I don’t think there’s enough context in the question, but typically, I would opt for creating a stored procedure that would perform the query I need based on certain parameters.
Some resources that might be helpful: