[英]how to insert multiple items of listbox in access database in c#
I have write this code but it only insert one not multiple items... 我写了这段代码,但它只插入一个而不是多个项目......
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
ad.InsertCommand = new OleDbCommand("insert into Map_Data (Material_Code,Product_Id) values(@Material_Code,@Product_Id)", con);
ad.InsertCommand.Parameters.Add("@Material_Code", OleDbType.Integer).Value =Convert.ToInt32(listBox1.SelectedValue);
listBox1.Items.Remove(listBox1.SelectedItem);
ad.InsertCommand.Parameters.Add("@Product_Id", OleDbType.Integer).Value = count;
}
con.Open();
ad.InsertCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record is successfully Save In The Database");
your 你的
ad.InsertCommand.ExecuteNonQuery();
needs to be inside the for loop. 需要在for循环中。
right now, it is outside the for loop and hence called only one. 现在,它在for循环之外,因此只调用一个。 also because it is a multi row insert you're trying, you're better off wrapping it in a oledb transaction to avoid data loss/inconistencies..
也因为它是你正在尝试的多行插入,你最好将它包装在oledb事务中,以避免数据丢失/不一致。
basically, 基本上,
It only inserts one row -the last one- because that's how many times you are calling ExecuteNonQuery
. 它只插入一行 - 最后一行 - 因为这是你调用
ExecuteNonQuery
。 If you want to insert every singe row, then move your closing curly bracket right after con.Close();
如果要插入每个
con.Close();
,则在con.Close();
之后con.Close();
移动结束花括号con.Close();
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
ad.InsertCommand = new OleDbCommand("insert into Map_Data (Material_Code,Product_Id) values(@Material_Code,@Product_Id)", con);
ad.InsertCommand.Parameters.Add("@Material_Code", OleDbType.Integer).Value =Convert.ToInt32(listBox1.SelectedValue);
listBox1.Items.Remove(listBox1.SelectedItem);
ad.InsertCommand.Parameters.Add("@Product_Id", OleDbType.Integer).Value = count;
con.Open();
ad.InsertCommand.ExecuteNonQuery();
con.Close();
}
MessageBox.Show("Record is successfully Save In The Database");
You may want to add some sort of try/catch
blocks in case you get problems opening the connection or executing the actual statement itself. 您可能希望添加某种
try/catch
块,以防您在打开连接或执行实际语句本身时遇到问题。 Also, you don't need to open/close the connection inside the for
loop. 此外,您无需打开/关闭
for
循环内的连接。 It should be enough with opening the connection outside the for and then closing it after the for block. 打开for之外的连接,然后在for block之后关闭它就足够了。 But again, I suggest you add
try/catch
or use using
statements instead. 但同样,我建议您添加
try/catch
或使用using
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.