Saturday, January 3, 2015

Add a new Row to DataTable in DataSet and Push the update to Database


Example is as below:

            string connectionString = "Data Source=****;Initial Catalog=master;Persist Security Info=True;User ID=**;Password=****";

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand("select top 10 * from Test", conn))
                {

                    conn.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);

                    DataRow row = ds.Tables[0].NewRow();
                    row["EID"] = "006";
                    row["Name"] = "Saman";
                    row["Tel"] = "01115342";
                    row["Residence"] = "Galle, Sri Lanka";

                    ds.Tables[0].Rows.Add(row);

                    //Update Database
                    SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
                    cb.DataAdapter.Update(ds.Tables[0]);
                }
            }

No comments:

Post a Comment