将组合框项添加到数据库

时间:2016-01-03 05:47:00

标签: c# sql-server database forms combobox

有点麻烦。我正在尝试将组合框项添加到我的数据库中,但它不起作用。

代码:

string con = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
string connectionString = con;
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand cmd = new SqlCommand("INSERT INTO JobRoles (Jobroles) VALUES (@jr)");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connection;
    cmd.Parameters.AddWithValue("@jr", comboBox1.Items.ToString());

    connection.Open();
    try
    {
        cmd.ExecuteNonQuery();
    }
    catch (Exception)
    {
        MessageBox.Show("Datebase error. Please contact software engineer.", "Error 303");
        return;
    }

我正在尝试在我的数据库中为每个组合框项创建一个新行,但所有组合框项都出现在一个单元格中,这将给我这个:

System.Windows.Forms.ComboBox+ObjectCollection

是否可以将组合框项添加到我的数据库中,并且每个组合框项在数据库中创建一个新行?谢谢!抱歉有任何困惑。

1 个答案:

答案 0 :(得分:0)

您不应该在一个命令中添加整个项目。相反,你应该使用foreach循环并逐个添加oitems。

string con = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
string connectionString = con;

foreach (var item in comboBox1.Items) //loop to go through the items one by one
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("INSERT INTO JobRoles (Jobroles) VALUES (@jr)");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = connection;
        cmd.Parameters.AddWithValue("@jr", item.ToString()); //Add each item to database separately 

        connection.Open();
        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (Exception)
        {
            MessageBox.Show("Datebase error. Please contact software engineer.", "Error 303");
            return;
        }
    }
}