1

我在Visual Studio 2010中創建了一個Windows Form,其中ComboBoxLocal Database。數據庫有一個表,其列中的行的列數要在組合框中列出。我怎樣才能做到這一點?填充組合框

我試着通過IDE添加一個data source與我感興趣的列,但它沒有工作。


我創建了一個Windows Forms Application與含有ComboBox一個Windows Form

                                                                                                                      enter image description here

我創建了一個Local Database含有Table與單個列和三個測試行。

                                                                                                                          enter image description here

我加了一個data source包含我感興趣的列。

    enter image description here

最後,我綁定的組合框的數據源,但結果卻是陌生的。

                                      enter image description here

+0

請發佈您迄今爲止編寫的代碼。我們在這裏不是心理學家;只是同類的書呆子。 – Brian

+0

@Brian,我修正了OP。 – Raptor

回答

1

這是原始代碼來完成你的要求:

string strCmd = ""; 
string strConn = ""; 
SqlConnection sqlConn = new SqlConnection(); 
SqlCommand sqlCmd = new SqlCommand(strCmd, sqlConn); 
SqlDataReader sqlRdr = new SqlDataReader(); 

sqlConn.Open(); 

if (comboBox1.Items.Count > 0) 
    comboBox1.Items.Clear(); 
sqlRdr = sqlCmd.ExecuteReader(); 

while (sqlRdr.Read()) 
    comboBox1.Items.Add(sqlRdr[0].ToString()); 

sqlRdr.Close(); 
sqlConn.Close(); 

雖然有一些事情需要先佈線。第一個是這樣的:

string strCmd = ""; // Insert your SQL statement here. 

二:

string strConn = ""; // Your db connection string goes here. 

三:

if (comboBox1.Items.Count > 0) // You don't have to use this. It just checks to see 
    comboBox1.Items.Clear();  // if there is anything in the combobox and clears it. 

最後,因爲你做的東西,處理表單和數據庫之間的交互,我強烈建議您使用SqlParameters來防止SQL Injection攻擊。