Thursday, October 22, 2020

Simple DataTable example in c sharp.

 




What are data tables?

DataTable represents data in table format as rows and columns.it is used for disconnected data access.

Dataset and data view both uses DataTable.

Create  sample Data table.

 I think following code is self explanatory.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Data;

 

namespace DataTable

{

    class Program

    {

        static void Main(string[] args)

        {

            //create new Data table

 

            System.Data.DataTable dt = new System.Data.DataTable("stud");

            DataColumn col;

 

            // create three columns in Data table

           

            col = new DataColumn();

            col.DataType = System.Type.GetType("System.Int32");

            col.ColumnName = "Id";

            col.ReadOnly = true;

            col.Unique = true;

            dt.Columns.Add(col);

 

            col = new DataColumn();

            col.DataType = System.Type.GetType("System.String");

            col.ColumnName = "Name";

            col.ReadOnly = false ;

            col.Unique = false;

            dt.Columns.Add(col);

 

            col = new DataColumn();

            col.DataType = System.Type.GetType("System.Int32");

            col.ColumnName = "Mark";

            col.ReadOnly =false;

            col.Unique = false;

            dt.Columns.Add(col);

 

 

            // create primary key

 

            DataColumn[] PrimaryKeyColumns = new DataColumn[1];

            PrimaryKeyColumns[0] = dt.Columns["Id"];

            dt.PrimaryKey = PrimaryKeyColumns;

 

           

 

            // create rows

 

            dt.Rows.Add(1, "karthieyan", 75);

            dt.Rows .Add(2, "Arun", 80);

            dt.Rows.Add(3, "hari", 78);

 

             // read rows from datatable

            foreach (DataRow tr in dt.Rows)

            {

                Console.WriteLine("Id={0}, Name={1}, Mark={2}", tr["Id"], tr["Name"], tr["Mark"]);

 

            }

 

            Console.ReadLine();

 

 

 

 

        }

    }

}

 

Output:



 

Thank you.

Muthu karthikeyan, Madurai.

Contact:

91 96293 29142

Tamil nad, India

 

 

No comments:

Post a Comment