简体   繁体   中英

Saving data from datagridview to SQL Server database

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();
            }
        }
    }
}

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!

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.

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();

}
  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM