1

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

我尝试data source通过 IDE 在我感兴趣的列中添加一个,但它不起作用。


我创建了Windows Forms Application一个Windows Form包含一个ComboBox.

                                                           在此处输入图像描述

我创建了一个Local Database包含Table单列和三个测试行的 a。

                                                             在此处输入图像描述

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

  在此处输入图像描述

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

                   在此处输入图像描述

4

1 回答 1

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

于 2013-06-25T20:30:38.817 回答