How to use DataTable in C#
By Tan Lee Published on Mar 13, 2021 20.1K
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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
- How to add class to tr using jQuery datatable
- How to disable sorting with jquery datatable
- How to hide “Showing 1 of N Entries” with jQuery datatables
- How to Change parameter used in datatables ajax url.Action on Ajax.reload
- How to assign an ID to the search input using datatable.net
- How to Convert DataTable to Html Table in C#
- How to fix 'Requested unknown parameter '6' for row 0, column 6'
- How to Add new row to datatable using jquery datatable
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
How to disable Windows Defender SmartScreen
Dec 24, 2024
Portal HTML Bootstrap
Nov 13, 2024
Base Responsive Material UI Admin Dashboard Template
Nov 18, 2024