How to use DataTable in C#

By FoxLearn 7/31/2024 2:03:39 AM   19.57K
In C#, DataTable is a fundamental part of ADO.NET, used to store in-memory data in tabular form. It’s commonly used for handling data retrieved from a database or other data sources.

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.

Create a new console application.

To create a DataTable, you need to instantiate it and define its structure (columns) and optionally its rows.

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();
    }
}

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.

VIDEO TUTORIAL