Tuesday 22 October 2013

How to create dynamic DataTable in C#.NET?

using System;
using System.Data;

class Program
{
    static void Main(string[] args)
    {
        DataTable table = GetTable();
    }
    static DataTable GetTable()
    {
        //Create new DataTable instance
        DataTable table = new DataTable("Indian Cricket Team");

        // Add Columns to table
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));
        table.Columns.Add("Batting style", typeof(string));
        table.Columns.Add("Bowling style", typeof(string));

        //Add Rows to Table
        table.Rows.Add("Mahendra Singh Dhoni", 32, "Right-handed", "Right medium");
        table.Rows.Add("Virat Kohli", 24, "Right-handed", "Right medium");
        table.Rows.Add("Virender Sehwag", 34, "Right-handed", "Off break");
        table.Rows.Add("Suresh Raina", 26, "Left-handed", "Off break");
        //.............
        //.............

        //Return the DataTable
        return table;
    }
}

No comments: