How to use DataTable in C#

How to use Datatable in C#. The DataTable is a central object in the ADO.NET library. Other objects that use the DataTable include the DataSet and the DataView

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Console Application. Name your project "DatatableExample" and then click OK

datatable in c#

Step 2: Add your code as below

class Program
{
    static void Main(string[] args)
    {
        //Create a new datatable
        using (DataTable dt = new DataTable("Test"))
        {
            //Add columns to datatable
            dt.Columns.Add("ID", typeof(int));
            dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };
            dt.Columns.Add("Dosage", typeof(int));
            dt.Columns.Add("Drug", typeof(string));
            dt.Columns.Add("Patient", typeof(string));
            dt.Columns.Add("Date", typeof(DateTime));
            //Add data to datatable
            dt.Rows.Add(1, 1, "Indocin", "David", DateTime.Now);
            dt.Rows.Add(2, 2, "Enebrel", "Sam", DateTime.Now);
            dt.Rows.Add(4, 3, "Hydralazine", "Christoff", DateTime.Now);
            dt.Rows.Add(7, 4, "Combivent", "Janet", DateTime.Now);
            dt.Rows.Add(7, 5, "Dilantin", "Melanie", DateTime.Now);
            //Using foreach to get data from datatable
            foreach (DataRow dr in dt.Rows)
            {
                Console.WriteLine("ID = {4} Dosage = {0}, Drug = {1}, Patient = {2}, Date = {3}", dr["Dosage"], dr["Drug"], dr["Patient"], dr["Date"], dr["ID"]);
            }
        }
        Console.ReadKey();
    }
}

VIDEO TUTORIALS

 

Related Posts