Reputation: 49
This code is working but I think something is missing because it only works if I add one row at a time. How can I store many rows at a time?
foreach (ListViewItem item in listView1.Items)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=ZON-PC;Initial Catalog=RestaurantPOSSOC;Integrated Security=True");
con.Open();
SqlCommand _sqlcommand = new SqlCommand("insert into OrderInfo (ProductName,Quantity,Price)values('" + listView1.Items[i].SubItems[0].Text + "','" + listView1.Items[i].SubItems[1].Text + "','" + listView1.Items[i].SubItems[2].Text + "')", con);
SqlDataReader _sqldatareader = _sqlcommand.ExecuteReader();
_sqldatareader.Read();
con.Close();
}
}
Upvotes: 0
Views: 1719
Reputation: 1
Add this under button click or any, before that you should open a SqlConnection
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
foreach (ListViewItem item in lvPOItem.Items)
{
SqlCommand cmd = new SqlCommand("INSERT INTO PurchasePOItems (PO_ItemName, PO_Specs, PO_PONumber)values(@PO_ItemName, @PO_Specs,@PO_PONumber)", conn);
conn.Open();
cmd.Parameters.AddWithValue("@PO_ItemName", item.SubItems[0].Text);
cmd.Parameters.AddWithValue("@PO_Specs", item.SubItems[1].Text);
cmd.Parameters.AddWithValue("@PO_PONumber", cbPurchaseOrderNo.Text);
cmd.ExecuteNonQuery();
conn.Close();
}
Upvotes: 0
Reputation: 48826
First: regardless of what method is used, you really need to clean up the external resources. Both the SqlConnection
and SqlCommand
objects have a .Dispose()
method and should be used in a using()
construct / macro. The using handles both the .Dispose()
as well as a basic try / finally to ensure that the .Dispose()
method is called, even if an error occurs.
Second: if you are using SQL Server 2008 or newer, you should check out Table Valued Parameters (TVPs) as they will eliminate the SQL Injection issues and increase performance.
I have examples of doing this in the following answers:
Upvotes: 0
Reputation: 1636
There are a couple of things I would change for your routine:
So in pseudocode:
using (connection = new(...))
con.open
foreach(item)
command = new command()
command.ExecuteNonQuery()
con.close
Upvotes: 1
Reputation:
Not an answer, but you really should change your starting code to at least this:
SqlConnection con = new SqlConnection("Data Source=ZON-PC;Initial Catalog=RestaurantPOSSOC;Integrated Security=True");
con.Open();
foreach (ListViewItem item in listView1.Items)
{
SqlCommand _sqlcommand = new SqlCommand("insert into OrderInfo (ProductName,Quantity,Price)values('" + item.SubItems[0].Text + "','" + item.SubItems[1].Text + "','" + item.SubItems[2].Text + "')", con);
SqlDataReader _sqldatareader = _sqlcommand.ExecuteReader();
_sqldatareader.Read();
}
con.Close();
And you really also need to parameterize your query and add some exception handling.
Upvotes: 0