1

Below is code in which I have written only save first row value in database but when I try to save multiple row value it gives an error. I don't know how to use loop in this code and where to use loop to insert multiple rows in database at once.

How do I save DataGridView values into a SQL Server database?

private void button1_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("INSERT INTO datagrid (sr, name, email, tel_no) VALUES(@c1,@c2,@c3,@c4)", cs);
    {
        cmd.Parameters.Add(new SqlParameter("@C1", SqlDbType.VarChar));
        cmd.Parameters.Add(new SqlParameter("@C2", SqlDbType.VarChar));
        cmd.Parameters.Add(new SqlParameter("@C3", SqlDbType.VarChar));
        cmd.Parameters.Add(new SqlParameter("@C4", SqlDbType.VarChar));

        cs.Open();

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            {
                if (!row.IsNewRow)
                {
                    cmd.Parameters["@C1"].Value = row.Cells[0].Value;
                    cmd.Parameters["@C2"].Value = row.Cells[1].Value;
                    cmd.Parameters["@C3"].Value = row.Cells[2].Value;
                    cmd.Parameters["@C4"].Value = row.Cells[3].Value;
                    cmd.ExecuteNonQuery();
                }
                cs.Close();
            }
        }
    }
}
7
  • What is the error? I bet its something to do with a closed connection - you're closing the connection at the end of your for each code block, so it will only save the first row, no matter how many rows you have. Move cs.Close(); outside your for each loop.
    – Tim
    Jun 25, 2013 at 5:42
  • You don't need the foreach loop. Jun 25, 2013 at 5:47
  • @SaroopTrivedi - If OP is saving multiple rows from a DataGridView, they need some sort of loop.
    – Tim
    Jun 25, 2013 at 6:08
  • 1
    @Tim: Then need to put the con.Open() and con.Close() into If condition. Because He try to open Con.open one time and close it all time. Jun 25, 2013 at 6:34
  • 1
    @Edper - working on that now...was hoping for a little more info from OP, but will go with what is there and hope they find it helpful.
    – Tim
    Jun 25, 2013 at 6:43

4 Answers 4

3

There's some information that would be nice to have that you didn't put in your original question:

  1. cs is most likely a SqlConnection, and since you say it works inserting one row I'm guessing it's a global (class level) variable and is created somewhere else. I would do a little bit differently (see my code example for the reason why).

  2. What error are you getting? Based on the problem description, I'll bet it is a closed connection (because you're closing it at the end of your foreach code block, when you should be closing it outside the foreach code block).

So, with that said, here's something that might do the trick for you:

private void button1_Click(object sender, EventArgs e)
{

    using (SqlConnection conn = new SqlConnection(connectionString))
    {

        cs.Open();

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {

            if (!row.IsNewRow)
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO datagrid (sr, name, email, tel_no) VALUES(@c1,@c2,@c3,@c4)", conn))
                {

                    cmd.Parameters.AddWithValue("@C1", row.Cells[0].Value);
                    cmd.Parameters.AddWithValue("@C2", row.Cells[1].Value);
                    cmd.Parameters.AddWithValue("@C3", row.Cells[2].Value);
                    cmd.Parameters.AddWithValue("@C4", row.Cells[3].Value);

                    cmd.ExecuteNonQuery();

                }
            }
        }
    }
}

In the example above, I use using blocks for the SqlConnection and SqlCommand objects. The using block ensures that the resources are properly cleaned up when the using block is exited - this way you don't have to worry about things like when to call conn.Close(), as the using block will take care of that for you.

Also, I create the SqlConnection in the method. The connectionString in this case would be a string variable (at the class level, so all methods that need it can access it) holding the connection string.

Finally, I create the SqlCommand in the if block, which will only be entered if the !row.IsNewRow expression evaluates to true. I'm not 100% sure you can reassign values to a an existing command's parameters (most likely you can, but...)

I would also suggest including some error handling in case something goes wrong with the insert.

Hopefully this addresses the questions/issues you have. If not, please provide more detail so we can better assist you. Happy coding!

1
  • thanks tim as you specifies issue with cs.close, in same code i changed the position of connection close and the same code worked properly Jun 25, 2013 at 10:42
0

The problem is that cs is closed more times than it is opened.

You open the connection, insert, but then try to close for each iteration.

Either you should open a connection for each iteration, or you should see how to do everything with only only connection.

0
int ab;

 int PIrowss = dataGridView2.Rows.Count;

 for (ab = 0; ab < PIrowss; ab++)

 {

 PiCGetAutID();

 purchaeOrder.pcautoid = Catget;

 purchaeOrder.ponum = label119.Text;

 purchaeOrder.col1 = dataGridView2.Rows[ab].Cells[0].Value.ToString();

 purchaeOrder.col2 = dataGridView2.Rows[ab].Cells[1].Value.ToString();

 purchaeOrder.col3 = dataGridView2.Rows[ab].Cells[2].Value.ToString();

 purchaeOrder.col4 = dataGridView2.Rows[ab].Cells[3].Value.ToString();

  purchaeOrder.col5 = dataGridView2.Rows[ab].Cells[4].Value.ToString();


 purchaeOrder.POcSave();

}
-1
  private void button1_Click(object sender, EventArgs e)
        {                  
SqlConnection conn = new SqlConnection();
conn.Open();

SqlCommand comm = new SqlCommand();
comm.Connection = conn;

string sr = null;
string name = null;
string email = null;
string tel_no = null;


for (int i = 0; i <= this.DataGridView1.Rows.Count; i++) {
sr == this.DataGridView1.Rows(i).Cells(0).Value.ToString()
name == this.DataGridView1.Rows(i).Cells(1).Value.ToString()
email == this.DataGridView1.Rows(i).Cells(2).Value.ToString()
tel_no == this.DataGridView1.Rows(i).Cells(3).Value.ToString()

 comm.CommandText = "insert into mytable(name,age) values('" & name & "','" & age& "')"
   comm.ExecuteNonQuery()

conn.Close()


}

}

Try this and see. It should work

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.