[英]Add combo box items to database
Having a little trouble. 有一点麻烦。 I'm trying to add combobox items to my database but It doesn't work.
我正在尝试将组合框项目添加到我的数据库中,但是它不起作用。
code: 码:
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;
}
I'm trying to create a new row per combo box item in my database but all the combo box items appear in a single cell which will give me this: 我正在尝试在数据库中为每个组合框项目创建一个新行,但是所有组合框项目都显示在单个单元格中,这将为我提供以下信息:
System.Windows.Forms.ComboBox+ObjectCollection
is it possible to add combo box items into my database and with each combo box item creates a new row in the database? 是否可以将组合框项目添加到我的数据库中,并且每个组合框项目在数据库中创建一个新行? Thanks!
谢谢! Sorry for any confusion.
抱歉给您带来任何混乱。
You shouldn't add the whole items in one command. 您不应该将全部项目添加到一个命令中。 Instead you should use a
foreach
loop and add the oitems one by one. 相反,您应该使用
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.