简体   繁体   English

我想将列表框项目插入数据库,数据库值应为从其他表中获取的整数

[英]I want to insert the listbox items into the database where database value should be integer which is fetched from other table

I'm new to C#. 我是C#的新手。 Please help me to build query 请帮我建立查询

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();
    }
}

This is the query I developed. 这是我开发的查询。

Thanks in advance 提前致谢

As I understand you need something like this 据我了解,您需要这样的东西

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();
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM