Wednesday, 2 July 2014

How to Create DataTable Programmatically in C#, ASP.NET

Many times we have the requirement where we have to create DataTable dynamically. In this Post, I have put the simple code for creating DataTable programmatically in C#.
        // Create a DataTable instance
        DataTable dtable = new DataTable();

        // Create columns for DataTable named 'dtable'
        DataColumn col1 = new DataColumn("ID");
        DataColumn col2 = new DataColumn("Name");
        DataColumn col3 = new DataColumn("City");
        DataColumn col4 = new DataColumn("State");

        // Define DataType of the Columns
        col1.DataType = System.Type.GetType("System.Int");
        col2.DataType = System.Type.GetType("System.String");
        col3.DataType = System.Type.GetType("System.String");
        col4.DataType = System.Type.GetType("System.String");

        // Add Columns into DataTable named 'dtable'
        dtable.Columns.Add(col1);
        dtable.Columns.Add(col2);
        dtable.Columns.Add(col3);
        dtable.Columns.Add(col4);

        // Create a Row in the DataTable named 'dtable'
        DataRow row = dtable.NewRow();

        // Fill All Columns with Data
        row[col1] = 111;
        row[col2] = "Demo";
        row[col3] = "My City";
        row[col4] = "My State";

        // Add the Row into DataTable
        dtable.Rows.Add(row);
Note:- DataTable is a class which comes under System.Data namespace of Dot Net Framework. So you have to include this namespace before using it.


That’s it!!…..Happy Programming...

No comments:

Post a Comment