Problem solve Get help with specific problems with your technologies, process and projects.

Column name in a combo box

I am trying to create a user form which allows a user to select a column from a combo box and then enter the appropriate data for the rest of the query in a text box control.

Is it possible to build a SELECT statement using the value in a combo box field for the column name? I know that you can use the contents of a textbox control for the WHERE clause.

Here's what I am attempting in code. VB.net and ADO.net.

Dim strSQL2 As String = "SELECT *  from aTable 
 WHERE  '" & ComboBox1.Text & "'
     =  '" & TextBox1.Text & "' "

 Dim cmd As New OleDbCommand(strSQL2, Conn)
 Dim rdr As OleDbDataReader
 rdr = cmd.ExecuteReader
 While rdr.Read
   ListBox1.Items.Add(rdr("Case_id") & "  " 
   & rdr("LastName") & "  " 
   & rdr("FirstName") & "  " 
   & rdr("Mi"))
  End While

Thanks for your help.

The answer is yes, it is possible.

Since you are building an SQL string, you can assemble any parts of it from all sorts of sources -- form controls, default variables, data from other tables, and so on.

But please don't ask me to look at code. My expertise is limited to SQL (and enough ColdFusion to create simple data-driven Web pages).

Assuming you've followed the syntax conventions of your language, the strSQL2 string looks like it would work, provided that you remove the single quotes around the column name. The quotes turn it into a string literal in SQL, and so it would likely never match the textbox contents (unless, you know, you happened to be searching for the name of that column).

Dig Deeper on SQL Server Database Modeling and Design

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.