After modifying the Datatable, you can update it to the database like this:
string connString = @"connString";
string insertString = @"insert into ScoreTable values(@id,@name,@math,@science,@english,@history)";
SqlCommand insertCommand = new SqlCommand(insertString);
insertCommand.Parameters.Add("@name", SqlDbType.NVarChar, 10, "Name");
insertCommand.Parameters.Add("@math", SqlDbType.Float, 2, "Math");
insertCommand.Parameters.Add("@science", SqlDbType.Float, 2, "Science");
insertCommand.Parameters.Add("@english", SqlDbType.Float, 4, "English");
insertCommand.Parameters.Add("@history", SqlDbType.Float, 4, "History");
insertCommand.Parameters.Add("@id", SqlDbType.Int, 4, "id");
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
insertCommand.Connection = connection;
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.InsertCommand = insertCommand;
var dataTable = (DataTable)stuDetBindingSource.DataSource;
adapter.Update(dataTable);
Console.WriteLine("Successfully to update the table.");
}
}
Or use SqlCommandBuilder to do it more simply:
string connString = @"connString";
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlCommand selectCommand = new SqlCommand(@"select * from scoreTable");
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
adapter.UpdateCommand = cb.GetUpdateCommand();
var dataTable = (DataTable)stuDetBindingSource.DataSource;
adapter.Update(dataTable);
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.