How To Save Datagridview Data To Database In C Windows

[Solved] How To Save Datagridview Data To Database In C Windows | Vb - Code Explorer | yomemimo.com
Question : how to save datagridview data to database in c# windows application

Answered by : homeless-hamerkop-c6y0zbl3y0eo

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

Source : https://stackoverflow.com/questions/36620479/saving-datagridview-data-to-sql-server-database-winform | Last Update : Sat, 15 May 21

Answers related to how to save datagridview data to database in c windows application

Code Explorer Popular Question For Vb