Juan Filipe
Juan Filipe

Reputation: 403

Add item to comboBox from SQL query

hey guys I want to Add Item to my ComboBox in vb.net. But the data I need is on my database.

I have here a SQL Query statement :

"SELECT DISTINCT(Tags) from Legal_Records"

what I want to do is to add the Result of this SQL Query to my ComboBox.

anyone can help me with this, make it simple tnx guys! :)

Upvotes: 1

Views: 19991

Answers (3)

user2984194
user2984194

Reputation: 1

here is my sample

    cbsection.Items.Clear()
    strsql = "select DISTINCT(section)  from sassign where grade like @field1"
    sqlcmd = New SqlClient.SqlCommand(strsql, sqlconn)
    With sqlcmd
        .Parameters.AddWithValue("@field1", cbgrade.Text)
    End With
    sqldr = sqlcmd.ExecuteReader
    While (sqldr.Read())
        With cbsection.Items.Add(sqldr("section"))
        End With
    End While
    sqlcmd.Dispose()
    sqldr.Close(

Upvotes: 0

E-r Gabriel Doronila
E-r Gabriel Doronila

Reputation: 533

you can make a datagridview look like a combobox..

remove the rowheaders and column headers.. you can replicate the dropdown action by adding an "arrow down" button.. add an event on arrowdown button click.. it should show the datagridview.. and if you click a cell on the datagridview.. you should copy the contents of the chosen cell and copy it to your textbox, after that hide the datagridview..

it takes only 3 controls* and with that you can easily manage your datasource (using datagridview)..

* (1)textbox and (2)arrow button down - to make it look like a combobox.. last is the (3)datagridview

Upvotes: 1

David Venegoni
David Venegoni

Reputation: 508

You may have more than a single result returned from that query, but here is how to go about doing what you want:

  1. You need some sort of connection, if you don't already have one:

    Dim conn As SqlConnection = New SqlConnection('connection string)    
    conn.Open()
  2. You have the command done, now just do something like:

    Dim command As SqlCommand = New SqlCommand("SELECT DISTINCT(Tags) from Legal_Records", conn)
  3. Now, you need a reader, like so:

    Dim reader As SqlDataReader = command.ExecuteReader()                   
    'your query will return an array of objects, unless you know there will be only one value to return, if that is the case, you can use command.ExecuteScalar() which will return only the first column of the first row
    
    While reader.Read()  
    ComboBox1.Items.Add(reader.GetString(0)) 'You can also do GetInt32, GetDouble, etc.  Everytime you call GetString or whatever you chooose, it will move to the next item in the object array                                                   `

That is it, hope that helps and don't forget to close and dispose of all your resources.

Upvotes: 0

Related Questions