c# datagridview save changes to database code example

Example: how to save datagridview data to database in c# windows application

private void btn_Save_Click(object sender, EventArgs e)
{
    string constring = @"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";
    SqlConnection con = new SqlConnection(constring);
    SqlTransaction transaction = con.BeginTransaction();
    try
    {
        con.Open();
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_prospects ([prospectid], [firstname], [lastname], [height], [weight], [age], [college])VALUES(@prospectid, @firstname, @lastname, @height, @weight, @age, @college)", con))
            {
                cmd.Parameters.AddWithValue("@prospectid", row.Cells["prospectid"].Value);
                cmd.Parameters.AddWithValue("@firstname", row.Cells["firstname"].Value);
                cmd.Parameters.AddWithValue("@lastname", row.Cells["lastname"].Value);
                cmd.Parameters.AddWithValue("@height", row.Cells["height"].Value);
                cmd.Parameters.AddWithValue("@weight", row.Cells["weight"].Value);
                cmd.Parameters.AddWithValue("@age", row.Cells["age"].Value);
                cmd.Parameters.AddWithValue("@college", row.Cells["college"].Value);
                cmd.Transaction = transaction;
                cmd.ExecuteNonQuery();
            }
        }
        transaction.Commit();
        con.Close();
        MessageBox.Show("Successfully Saved!");
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        con.Close();
        MessageBox.Show(ex.Message);
    }
}