0

This code is working if my listview has only 1 row. But if the listview has two or more rows, it double~triple etc.

foreach(ListViewItem ItemRow in this.listViewPOS.Items)
{
    for (int i = 0; i < listViewPOS.Count; i++)
    {
        SQLConn.sqL = "INSERT INTO OrderDetails(ProductID, OrderID, SRP, Quantity, Discount, Total) VALUES('" + ItemRow.SubItems[0].Text + "'," +
                "'" + OrderID + "', '" + ItemRow.SubItems[3].Text + "', '" + ItemRow.SubItems[4].Text + "', '" + ItemRow.SubItems[5].Text + "', '" + ItemRow.SubItems[6].Text + "')";

        SQLConn.ConnDB();
        SQLConn.cmd = new SqlCommand(SQLConn.sqL, SQLConn.conn);
        SQLConn.cmd.ExecuteNonQuery();
    }
}
2
  • 1
    SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection - check out Little Bobby Tables Commented May 24, 2018 at 4:20
  • alright, i will change it.. thanks for the reminder Commented May 24, 2018 at 4:54

1 Answer 1

2

It seems that you are looping the item list two times one using foreach and the second using for loop use either one

eg

foreach(ListViewItem ItemRow in this.listViewPOS.Items)
{
            SQLConn.sqL = "INSERT INTO OrderDetails(ProductID, OrderID, SRP, Quantity, Discount, Total) VALUES('" + ItemRow.SubItems[0].Text + "'," +
                "'" + OrderID + "', '" + ItemRow.SubItems[3].Text + "', '" + ItemRow.SubItems[4].Text + "', '" + ItemRow.SubItems[5].Text + "', '" + ItemRow.SubItems[6].Text + "')";

        SQLConn.ConnDB();
        SQLConn.cmd = new SqlCommand(SQLConn.sqL, SQLConn.conn);
        SQLConn.cmd.ExecuteNonQuery();
   }
Sign up to request clarification or add additional context in comments.

2 Comments

Use a parametric query to prevent a SQL Injection attack.
@RezaAghaei .. great advice..I skipped it as Little Bobby Tables – marc_s already advised it in command. and I don't want the beginner to get confused trying something new in mid of this issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.