Print DataTable : DataTable « Database ADO.net « C# / C Sharp






Print DataTable

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

class Program {
    static void Main(string[] args) {
        DataSet carsInventoryDS = new DataSet("Inventory");
        carsInventoryDS.ExtendedProperties["TimeStamp"] = DateTime.Now;
        carsInventoryDS.ExtendedProperties["Company"] = "Name";

        DataColumn carIDColumn = new DataColumn("CarID", typeof(int));
        carIDColumn.ReadOnly = true;
        carIDColumn.Caption = "Car ID";
        carIDColumn.AllowDBNull = false;
        carIDColumn.Unique = true;
        carIDColumn.AutoIncrement = true;
        carIDColumn.AutoIncrementSeed = 0;
        carIDColumn.AutoIncrementStep = 1;
        carIDColumn.ColumnMapping = MappingType.Attribute;

        DataColumn carMakeColumn = new DataColumn("Make", typeof(string));
        DataColumn carColorColumn = new DataColumn("Color", typeof(string));
        DataColumn carPetNameColumn = new DataColumn("PetName", typeof(string));
        carPetNameColumn.Caption = "Name";

        DataTable inventoryTable = new DataTable("Inventory");
        inventoryTable.Columns.AddRange(new DataColumn[] { carIDColumn, carMakeColumn, carColorColumn, carPetNameColumn });

        inventoryTable.PrimaryKey = new DataColumn[] { inventoryTable.Columns[0] };

        DataRow carRow = inventoryTable.NewRow();
        carRow["Make"] = "B";
        carRow["Color"] = "C";
        carRow["PetName"] = "A";
        inventoryTable.Rows.Add(carRow);
        carRow = inventoryTable.NewRow();
        carRow["Make"] = "S";
        carRow["Color"] = "R";
        carRow["PetName"] = "E";
        inventoryTable.Rows.Add(carRow);

        carsInventoryDS.Tables.Add(inventoryTable);
        PrintTable(carsInventoryDS.Tables["Inventory"]);
    }

    private static void PrintTable(DataTable dt) {
        DataTableReader dtReader = dt.CreateDataReader();
        while (dtReader.Read()) {
            for (int i = 0; i < dtReader.FieldCount; i++) {
                Console.Write("{0} = {1} ",
                    dtReader.GetName(i).Trim(),
                    dtReader.GetValue(i).ToString().Trim());
            }
            Console.WriteLine();
        }
        dtReader.Close();
    }
}
           
         
  








Related examples in the same category

1.illustrates the use of adding, modifying, and deleting a row in a DataTable object and synchronizing those changes with the
2.illustrates how to specify and use a relationship between two DataTable objects
3.Filter sort based on DataTableCollection
4.Modify DataTable: insert data to database table
5.Move DataRow in a DataTable