pick value from listbox and use in sql query as column name.query dynamically pick column name from variable

StackOverflow https://stackoverflow.com/questions/23557389

  •  18-07-2023
  •  | 
  •  

Pregunta

I have VB.net app that when run you select from listbox values that should then be used in select query.Then click save command button. see vb code snippet below

transport = lsttrans.SelectedItem
    leave = lstleave.SelectedItem

then query like below.Note transport and leave are dummy columns not on existing employee table.

select employeeid,'' as transport_allowance,'' as leave from employees

i wish to somehow create new query to be something close to the below using my selected values in listbox.

select employeeid,transport,leave from employees
¿Fue útil?

Solución

Use String.Format(). Here is the example assuming transport and leave variables are already declared:

Dim myQueryTemplate As String = "SELECT employeeid, {0}, {1} FROM employees"
Dim myFinalQuery as String = String.Format(myQueryTemplate, transport, leave)

If you will debug that, the value of myFinalQuery will be:

"SELECT employeeid, transport, leave FROM employees"

Add more if needed. From my given example, the next parameter will be {2} and so on.

Otros consejos

Do you already know how to retrieve data from a database in VB.NET? If not then you should read up on ADO.NET.

Assuming that you know how ADO.NET works, your SQL is simply a String, so you can build it up from parts the same way you can any other String. In this case, I would suggest calling the String.Format method to insert the column names into a query template.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top