I have winform that gets id
from comboBox
and multiple values from listBox
then I need to store this listBox
items with id of my comboBox
item.
**Current behavior`
If there is only one item in my listBox
it stores. But if there is multiple items (which is purpose of using listBox
) it return following error:
Message: Procedure or function InsertSerial has too many arguments specified.
Expected behavior
Get all items in listBox
and add them to database together (bulk insert)
Code
Table schema
CREATE TABLE [dbo].[Serials] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[ProductId] INT NOT NULL,
[Serial] VARCHAR (50) NOT NULL,
[Sold] BIT DEFAULT ((0)) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Serials_Products] FOREIGN KEY ([ProductId]) REFERENCES [dbo].[Products] ([Id])
);
StoredProcedur
CREATE PROCEDURE [dbo].[InsertSerial]
@ProductId INT,
@Serial NVARCHAR(50),
@Sold INT
AS
begin
INSERT into Serials(ProductId, Serial, Sold) values (@ProductId,@Serial,@Sold);
end
form
// save button
private void snStoreBtn_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyApp.Properties.Settings.MyAppDatabaseString"].ConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using (SqlCommand cmd = new SqlCommand("dbo.InsertSerial", cn))
{
foreach (var item in listBox1.Items)
{
Console.WriteLine("Item::: {0}", item.ToString());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductId", selectedProductId);
cmd.Parameters.AddWithValue("@Serial", item.ToString()); //Message: Procedure or function InsertSerial has too many arguments specified.
cmd.Parameters.AddWithValue("@Sold", "0");
cmd.ExecuteNonQuery();
}
cn.Close();
}
backgroundWorker1.RunWorkerAsync();
progressBarStoringData.Visible = true;
progressLabel.Visible = true;
}
// clear the listBox
listBox1.Items.Clear();
}
catch (SqlException ex)
{
StringBuilder errorMessages = new StringBuilder();
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
}
Question
How exactly should I loop my listBox
items to be stored in database properly?