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攻击。