将组合框项添加到数据库

本文关键字:数据库 添加 组合 | 更新日期: 2023-09-27 18:28:43

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

法典:

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
是否可以将组合

框项添加到我的数据库中,并使用每个组合框项在数据库中创建新行?谢谢!很抱歉有任何困惑。

将组合框项添加到数据库

不应在一个命令中添加整个项目。相反,您应该使用 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;
        }
    }
}