0

I have been able to figure out how to populate my combo box with information pulled from a SQL query. What I need to do now is take the item selected from that combo box and run another query with that info using a button. This is what I have so far.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim myconn As New SqlClient.SqlConnection("server=myserver;UID=User;PWD=Password;database=myDB")
    Dim myTable As New DataTable()
    Dim myCmd As New SqlCommand()
    Dim myAdapter As New SqlDataAdapter(myCmd)

    myCmd.Connection = myconn
    myCmd.Connection.Open()

    myCmd.CommandText = "UPDATE myDB.<*Selected list from combo box*> SET example = x WHERE example = y"

    myCmd.ExecuteNonQuery()
    myCmd.Connection.Close()
    MsgBox("Done!")

End Sub

As you can see the issue is the portion I have named <Selected list from combo box> I am not asking for answers on how to do this, I am asking that you all point me in the right direction if possible.

Alejandro
  • 7,290
  • 4
  • 34
  • 59
A. Fuller
  • 1
  • 3
  • "myDB.<*Selected list from combo box*>" is confusing. This makes it appear as if your combo box is populated with table names in the myDB database, but you did not specifically say that. Are you trying to update a table that the user chooses from a list of table names in a combo box? – Brian Pressler Aug 31 '16 at 23:15
  • Yes I am. They will select the table for the drop down and click a button to "Update" a column in a table. – A. Fuller Sep 01 '16 at 01:59
  • For instance they will have several items populated depending on what is in the database at that time. They will select the one that they need to update then they will click the button that runs "UPDATE myDB.<*Selected list from combo box*> SET example = x WHERE example = y" on that selection. – A. Fuller Sep 01 '16 at 02:01

1 Answers1

0

If I understand your question, I believe all you need to do is build a string for your update statement to concatenate the table name in. Something like this would be functional:

myCmd.CommandText = "UPDATE myDB." & listbox1.SelectedItem.Value & " SET example = x WHERE example = y"

One important thing you want to keep in mind though is that a bad value in your list box could cause you to a security vulnerability called SQL Injection. So within your button procedure you might want to do some validation checks to be absolutely sure that the value in listbox1.SelectedItem.Value is strictly a valid table name that you allow to be updated before just passing it along as a SQL command.

Community
  • 1
  • 1
Brian Pressler
  • 6,653
  • 2
  • 19
  • 40