2016-01-03 148 views
0

有點麻煩。我試圖添加組合框項目到我的數據庫,但它不起作用。將組合框項目添加到數據庫中

代碼:

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 

是否可以將組合框項添加到我的數據庫中,並且每個組合框項在數據庫中創建一個新行?謝謝!對不起,有任何困惑。

回答

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; 
     } 
    } 
} 
相關問題