Create DataTable

ByEnrico

May 13, 2014

Data is read from a database. It is generated in memory from input. DataTable is ideal for storing data from any source. With it we take objects from memory and display the results in controls such as DataGridView.

The DataTable type is a powerful way to store data in memory. You may have fetched this data from a database, or dynamically generated it. We get a DataTable with four columns of type int, string and DateTime.

This DataTable could be persisted or displayed, stored in memory as any other object, or with helper methods manipulated.

using System; 
using System.Data;

class Program
{
static void Main()
{
//
// Get the DataTable.
// DataTable table = GetTable();
//
// Use DataTable here with SQL.
//
}

/// <summary>
/// This example method generates a DataTable.
/// </summary>
static DataTable GetTable()
{
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));

//
// Here we add five DataRows.
//
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

return table;
}
}

By Enrico

My greatest passion is technology. I am interested in multiple fields and I have a lot of experience in software design and development. I started professional development when I was 6 years. Today I am a strong full-stack .NET developer (C#, Xamarin, Azure)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.