[英]Add combo box items to database
有一點麻煩。 我正在嘗試將組合框項目添加到我的數據庫中,但是它不起作用。
碼:
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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.