C # write datagridview data to SQL table

I have four coloum tables in an SQL database. Information for the first three columns is provided by another source. Coloum 4 is set to null by default.

Then I get a win form with data that is populated with information from the sql database using the following code:

    public DataTable populateFormList()
    {


            SqlConnection con = new SqlConnection(Properties.Settings.Default.sqlConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT * FROM of_formlist_raw", con);
            con.Open();

            SqlDataReader reader = cmd.ExecuteReader();

            DataTable dt = new DataTable();
            dt.Load(reader);

            return dt;
}

datagridview2.DataSource = populateFormList();
datagridview2.Refresh();

Now this works great when getting my data.

The user can then make changes to the null values ​​in column 4.

How can I easily write these changes from the datatable back to the SQL table?

In other words, once there are additional values ​​on the datatable screen, how can I then save the updated information back to the SQL data from which it was originally obtained?

Thank.

0
source share
2

- (DataTable)datagridview2.DataSource :

private static void BulkInsertToSQL(DataTable dt, string tableName)
        {

                using (SqlConnection con = new SqlConnection(_DB))
                {
                    SqlBulkCopy sbc = new SqlBulkCopy(con);
                    sbc.DestinationTableName = tableName;

                    //if your DB col names don’t match your data table column names 100%
                    //then relate the source data table column names with the destination DB cols
                    sbc.ColumnMappings.Add("DBAttributeName1", "DTColumnName1");
                    sbc.ColumnMappings.Add("DBAttributeName2", "DTColumnName2");
                    sbc.ColumnMappings.Add("DBAttributeName3", "DTColumnName3");
                    sbc.ColumnMappings.Add("DBAttributeName4", "DTColumnName4");

                    con.Open();

                    sbc.WriteToServer(dt);
                    con.Close();
                }


        }
+2

2 , TableAdapter.

MSDN TableAdapter

BindingSources, , .

TableAdapter, , " Command".

0

All Articles