【问题标题】:Populating a Combo Box填充组合框
【发布时间】:2013-06-22 18:58:12
【问题描述】:

我在 Visual Studio 2010 中创建了一个Windows Form、一个ComboBox 和一个Local Database。数据库有一个表,其中包含我想在组合框中列出其行的列。我怎样才能做到这一点?

我尝试通过 IDE 在我感兴趣的列中添加data source,但没有成功。


我创建了一个Windows Forms Application,其中一个Windows Form 包含一个ComboBox

                                                         

我创建了一个 Local Database,其中包含一个带有单列和三个测试行的 Table

                                                          

我添加了一个data source,其中包含我感兴趣的列。

  

最后我把组合框绑定到数据源上,结果很奇怪。

                  

【问题讨论】:

  • 请贴出您目前编写的代码。我们在这里不是通灵者;只是书呆子。
  • @Brian,我修复了 OP。

标签: winforms visual-studio-2010 combobox datasource local-database


【解决方案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 攻击。

【讨论】:

    猜你喜欢
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2015-05-23
    相关资源
    最近更新 更多