1

Windows FormVisual Studio 2010 で、 with ComboBox、およびを作成しましたLocal Database。データベースには、コンボ ボックスに一覧表示する行を含む列を持つテーブルがあります。どうすればこれを達成できますか?

興味のある列を IDE から追加しようとしましたdata sourceが、うまくいきませんでした。


を含むでを作成しましWindows Forms Applicationた。Windows FormComboBox

                                                           ここに画像の説明を入力

1つの列と 3 つのテスト行Local Databaseを含むを作成しました。Table

                                                             ここに画像の説明を入力

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.

2番:

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.

最後に、フォームとデータベース間の対話を処理するものを作成しているため、 SQL インジェクション攻撃を防ぐためにSqlParametersを使用することを強くお勧めします。

于 2013-06-25T20:30:38.817 に答える