Reputation: 757
I've created a datagridview which is binded to a datatable. How would I add all of the contents in my datatable to the database with 1 buttonclick? for ex: I have inserted 5 values in my datatable. How would I insert all of the 5 datatable at once?
Upvotes: 2
Views: 2947
Reputation: 371
you can do something like this:
string ConnString= "Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Pooling=False";
private void button1_Click(object sender, EventArgs e)
{
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand(StrQuery, conn))
{
conn.Open();
comm.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
the ConnectionString you can get it from the property of you DB, also put " ' " in the Command when you want to insert value which is not number...
Upvotes: 1