2013-03-27 43 views
1

嘿傢伙我想添加項目到我的組合框在vb.net。但我需要的數據在我的數據庫上。從SQL查詢添加項目到組合框

我這裏有一個SQL查詢語句:

"SELECT DISTINCT(Tags) from Legal_Records" 

我想要做的就是添加這個SQL查詢的結果我的組合框。

任何人都可以幫助我,讓它變得簡單tnx傢伙! :)

+0

喜娟,你是如何在目前通過應用程序訪問數據庫(例如你使用實體框架,LINQ to SQL,直接對數據庫執行SqlCommands)?您訪問數據庫的方法將會影響到某人如何執行此操作的建議的最佳方式 – nkvu 2013-03-27 03:39:17

+0

您可以將其分爲兩個問題:1.如何從VB.net中通過數據庫獲取格式化數據? 2.如何將它們添加到VB.net的組合框中。兩者都可以通過Google輕鬆回答。 – iamsleepy 2013-03-27 03:44:31

+0

除了下面提供的答案,你還可以綁定你的數據表到像這樣的問題的組合框:http://stackoverflow.com/questions/15426218/vb-net-combobox-population-getting-index-of -the-1st-combobox/15426493#15426493 – 2013-03-27 04:10:58

回答

1

可以使一個DataGridView看起來像一個組合框..

刪除rowheaders和列標題..你可以通過添加「向下箭頭」按鈕複製的下拉作用..上arrowdown點擊按鈕添加一個事件..它應該顯示在DataGridView ..如果你點擊datagridview的單元格..你要的內容複製選定的細胞,並將其複製到文本框,在這之後隱藏的DataGridView ..

它只需要3個控件*,並且可以輕鬆管理您的數據源(使用datagridview)。

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

您可能不是從查詢返回一個結果多,但這裏是如何去這樣做你想要什麼:

  1. 你需要某種形式的連接,如果你不已經有一個:

    Dim conn As SqlConnection = New SqlConnection('connection string)  
    conn.Open()
  2. 你的命令來完成,現在只是做一些事情,如:

    Dim command As SqlCommand = New SqlCommand("SELECT DISTINCT(Tags) from Legal_Records", conn)
  3. 現在,你需要一個讀者,就像這樣:

    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             `

就是它,希望幫助,不要忘記關閉,所有資源的配置。

0

這裏是我的樣品

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(
+3

質量答案應包括解釋或代碼中最少的評論。 「代碼轉儲」通常被認爲是低質量的答案。請參閱[如何編寫好的答案?](http://stackoverflow.com/help/how-to-answer)。 – 2013-11-12 17:13:22