Add Row to DataTable : DataTable « ADO.Net « C# / CSharp Tutorial






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 employee 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"] = "w";

         DataRow newRow = dt.NewRow();
         newRow["firstname"] = "R";
         newRow["lastname"] = "B";
         newRow["titleofcourtesy"] = "Sir";
         newRow["city"] = "B";
         newRow["country"] = "USA";
         dt.Rows.Add(newRow);

         foreach (DataRow row in dt.Rows)
         {
            Console.WriteLine("{0} {1} {2}",
               row["firstname"].ToString().PadRight(15),
               row["lastname"].ToString().PadLeft(25),
               row["city"]);
         }
      }
      catch(Exception e)
      {
         Console.WriteLine("Error: " + e);
      }
      finally
      {
         conn.Close();
      }
   }
}








32.36.DataTable
32.36.1.Loop through DataTable by DataRow
32.36.2.Use DataTable to insert a Row
32.36.3.Add Row to DataTable
32.36.4.Accessing Data Values in a DataTable or DataSet
32.36.5.Adding Columns to DataTable
32.36.6.Adding Constraint to DataTable
32.36.7.Adding a Calculated Column to a DataTable
32.36.8.Adding a Column to a Child DataTable That Displays Data from the Parent Table
32.36.9.Adding a Column to a Parent DataTable That Aggregates a Child Table's Column Values
32.36.10.Creating a DataColumn and Adding It to a DataTable
32.36.11.Creating a DataTable and Adding It to a DataSet
32.36.12.Retrieving a Result Set Using a DataTable or a DataSet
32.36.13.Pop DataTable
32.36.14.Output Constraint Properties
32.36.15.Output the rows from the DataTable with foreach loop over DataRowCollection
32.36.16.Modify DataTable
32.36.17.Loop through the rows in DataTable
32.36.18.Creating Single- and Multi-Column Primary Keys
32.36.19.Creating a Unique Constraint
32.36.20.Append columns to DataTable
32.36.21.Accessing FirstName value in row 3 directly
32.36.22.Filter Sort
32.36.23.Retrieves a schema table for a query