How to use DataTable in C#

This post shows you how to use DataTable in C# .NET

A DataTable object resembles a database table and has a collection of DataColumns and DataRows.

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

To play the demo, you can create a new console application, then add your code as shown 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"]);

We will create a new DataTable, then add columns to the DataTable.

Finally, Add DataRow to the DataTable, if you want to get data from datatable in c#, you can use the foreach loop to get datarow in datatable.


Related Posts