Jun 24, 2011

C# DataTable Examples


You need to store data that was read from a database such as SQL Server or generated in memory from user input. DataTable is ideal for this purpose, as you can take objects from memory and display the results in controls such as DataGridView in Windows Forms. Through the descriptions here, we examine the DataTable type in the C# language.
DataTable is found in the System.Data namespace.
It stores data in memory from databases or user input. It helps with using DataGridView and SQL Server databases.

Example 1

First, the DataTable type is probably the most convenient and powerful way to store data in memory. You may have fetched this data from a database, or you may have generated it dynamically. In this example, we get a DataTable with four columns of type int, string and DateTime. This DataTable could then be persisted or displayed.
Program that uses DataTable [C#]

using System;
using System.Data;

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

    /// <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;
    }
}
Note on GetTable method. This method simply instantiates a new DataTable reference, adds four column collections to it, and then adds five drug and patient records. The next step to using this code could be to assign the DataSource to a Windows Forms control.

No comments:

Post a Comment