Mega Code Archive

 
Categories / C# Tutorial / ADO Net
 

Modify DataTable

using System; using System.Data; using System.Data.SqlClient;     class ModifyDataTable     {         static void Main(string[] args)         {             string connString = @"server = .\sqlexpress;integrated security = true;database = northwind";             string sql = @"select * from employees where country = 'UK'";             SqlConnection conn = new SqlConnection(connString);             try             {                 SqlDataAdapter da = new SqlDataAdapter();                 da.SelectCommand = new SqlCommand(sql, conn);                 DataSet ds = new DataSet();                 da.Fill(ds, "employees");                 DataTable dt = ds.Tables["employees"];                 dt.Columns["firstname"].AllowDBNull = true;                 dt.Rows[0]["city"] = "Wilmington";                 DataRow newRow = dt.NewRow();                 newRow["firstname"] = "Roy";                 newRow["lastname"] = "Beatty";                 newRow["titleofcourtesy"] = "Sir";                 newRow["city"] = "Birmingham";                 newRow["country"] = "UK";                 dt.Rows.Add(newRow);                 foreach (DataRow row in dt.Rows)                 {                     Console.WriteLine(row["firstname"]);                     Console.WriteLine(row["lastname"]);                     Console.WriteLine(row["city"]);                 }             }             catch (Exception e)             {                 Console.WriteLine("Error: " + e);             }             finally             {                 conn.Close();             }         }     }