2016-12-13 3 views
0

私はC#を初めて使い慣れました。クエリを作成するのを手伝ってくださいデータベースにリストボックス項目を挿入したいのですが、データベース値は他のテーブルからフェッチされた整数でなければなりません

for (int i = 0; i < lstCountry.Items.Count; i++) 
{ 
    if (lstCountry.Items[i].Selected == true) 
    { 
     cmd.CommandText = "INSERT ModuleMaster (ModuleName, Country, ModuleLeader, FirstAml, SecondAml,CoreTeamMember) VALUES (@ModuleName,@Country, @ModuleLeader, @FirstAml, @SecondAml, @CoreTeamMember)" 
     + "SELECT * FROM CountryMaster WHERE CountryName IN (" + lstCountry + ");"; 

     cmd.Connection = sqlConnection1; 

     cmd.Parameters.AddWithValue("@ModuleName", txtModuleName.Text); 
     cmd.Parameters.AddWithValue("@Country", lstCountry.Items[i].ToString()); 
     cmd.Parameters.AddWithValue("@ModuleLeader", ddModuleLeader.Text); 
     cmd.Parameters.AddWithValue("@FirstAml", ddFirstAML.Text); 
     cmd.Parameters.AddWithValue("@SecondAml", ddSecondAML.Text); 
     cmd.Parameters.AddWithValue("@CoreTeamMember", txtCoreMembers.Text); 

     sqlConnection1.Open(); 
     cmd.ExecuteNonQuery(); 
     sqlConnection1.Close(); 
    } 
} 

これは私が開発したクエリです。事前

+0

ようなものが必要理解しています。何をしたいのかははっきりしていません。 – anatol

+0

私はそこに国があるリストボックスを持っています。私は国を格納する必要がありますが、国のIDは、他のテーブルに存在する格納する必要があります –

+0

あなたはそれを実行しようとしましたか? – anatol

答えて

0

おかげで私はあなたが役に立つ答えを取得したい場合は、質問役立つ情報に追加してください。この

using (var connection = new SqlConnection(connectionString)) 
{ 
    using (var cmd = connection.CreateCommand()) 
    { 
     var selected_item = lstCountry.SelectedItem.ToString(); 
     cmd.CommandType = CommandType.Text; 
     cmd.CommandText = "INSERT ModuleMaster (ModuleName, Country, ModuleLeader, FirstAml, SecondAml, CoreTeamMember) " 
         + $"SELECT ModuleName, Country, ModuleLeader, FirstAml, SecondAml, CoreTeamMember FROM CountryMaster WHERE CountryName = {selected_item}"; 
     connection.Open(); 
     cmd.ExecuteNonQuery(); 
     connection.Close(); 
    } 
} 
関連する問題