Insert data into Sql Server DataTable from Datagridview

In this article we will learn how to insert data from Datagridview into Sql Server DataTable.

We have unbound Datagridview that contains data that will be inserted in "Article" DataTable.

Insert data into Sql Server DataTable from Datagridview

In button Save click event we add this code:

SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\database.mdf;Integrated Security=True;User Instance=True";
string insertcmd = "INSERT INTO [Article] (CodeArticle,LibArticle,Quantity)" +
                     "VALUES(@CodeArticle1,@LibArticle,@Quantity)";
SqlCommand cmd=new SqlCommand(insertcmd,con);
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
         cmd.Parameters.AddWithValue("@CodeArticle1", dataGridView1.Rows[i].Cells["codeArticleDataGridViewTextBoxColumn"].Value);
         cmd.Parameters.AddWithValue("@LibArticle",dataGridView1.Rows[i].Cells["libeArticleDataGridViewTextBoxColumn"].Value);
         cmd.Parameters.AddWithValue("@Quantity",dataGridView1.Rows[i].Cells["QuantityDataGridViewTextBoxColumn"].Value);
         cmd.ExecuteNonQuery();
         cmd.Parameters.Clear()
}
MessageBox.Show("Data saved successefully");
con.Close();


Insert data into Sql Server DataTable from Datagridview Insert data into Sql Server DataTable from Datagridview Reviewed by Bloggeur DZ on 10:50 Rating: 5

Aucun commentaire:

Fourni par Blogger.