DataTable in C#



Some times we have a need to store values temporarily. In Every time of process we can't store the values to SQL or MS access database. So to access temporary values we using data table in c#. The data table gives the convenient way to store the data in memory.

Creation of data table:

The syntax of the Datatable creation is

Datatable datatablename =new Datatable ();

Example:

Datatable dt =new Datatable ();

Here dt is a Datatable name and new represents creating a new Datatable with null value.

Add column:

To add a new column in Data table we using below syntax

dt.Columns.Add ("Columname");

Example:

dt.Columns.Add ("Name");

Here we created a "Name" column in Datatable dt.

Add Row and item:

Syntax of add row,

            datatablename.Rows.Add();
            DataRow datarowname;
            datarowname =datatablename.NewRow();
            datarowname["columnname"] = object;
            datatablename.Rows.Add(datarowname);

Example:

             dt.Rows.Add();
            DataRow dr;
            dr = dt.NewRow();
            dr["Name"] = "aaa";
            dt.Rows.Add(dr);

Delete Row:

Syntax for deletion:

datatablename.Rows [Rowvalue].Delete ();
datatablename.RemoveAt (Rowvalue);

Example

dt.Rows [0].Delete ();

dt.Rows.RemoveAt (0);
 

Up Next
    Ebook Download
    View all
    Learn
    View all