Click here to Skip to main content
15,906,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Can someone please help me to save
all the datagridview rows into a SQL table.

I tried saving it using a for loop, but it only
saves the first rows. If I insert more than one
row it simply doesn't save it.

This is what I have tried:

C#
private void SavedataGridTable()
        {
            ConnLibrary conn = new ConnLibrary();

            using (SqlCommand sqlcomm = new SqlCommand())
            {
                for (int i = 0; i < dgrLoadGrid.Rows.Count - 1; i++)
                {

                    strNameS = dgrLoadGrid[0, i].Value.ToString();
                    intPrice = Convert.ToInt32(dgrLoadGrid[1, i].Value);
                    intQuantity = Convert.ToInt32(dgrLoadGrid[2, i].Value);
                    dteNow = dateTimePicker1.Value;



                    sqlcomm.Connection = conn.Connection;
                    sqlcomm.CommandType = CommandType.StoredProcedure;
                    sqlcomm.CommandText = "usp_SaveSale";

                    sqlcomm.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = strNameS;
                    sqlcomm.Parameters.Add("@Price", SqlDbType.Int).Value = intPrice;
                    sqlcomm.Parameters.Add("@Quantity", SqlDbType.Int).Value = intQuantity;
                    sqlcomm.Parameters.Add("@Date", SqlDbType.Date).Value = dteNow;
                    sqlcomm.ExecuteNonQuery();
                    MessageBox.Show("Sale Done");
                }
            }
        }
Posted

1 solution

Try:
for (int i = 0; i < dgrLoadGrid.Rows.Count - 1; i++)
{
 using (SqlCommand sqlcomm = new SqlCommand())
 {
   ... // the code as it is


I would remove the MessageBox.Show("Sale Done"); though :)

Best regards
Espen Harlinn
 
Share this answer
 
Comments
Ben Paxton 30-Aug-11 17:42pm    
GREAT!! It worked thanks alot.
Espen Harlinn 30-Aug-11 17:44pm    
Good :)
Simon Bang Terkildsen 30-Aug-11 20:11pm    
+5
Espen Harlinn 31-Aug-11 10:08am    
Thank you, Simon!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900