How to create dynamic datatable in asp.net or C#

 Hi Friends ,
Here i am going to show how to create dynamic datatable . we need to create datatable at run time for this we use System.Data namespace because DataTable is Derived from this name space.
DataTable is Derived from




//Create a object of Datatable
        DataTable dynamicDataTable = new DataTable();

        //DataRow
        DataRow dynamicRow;
        //DataColumn for Name and Address
        DataColumn NameColumn = new DataColumn("Name", typeof(string));
        DataColumn AddColumn = new DataColumn("Address", typeof(string));

        //add Column to Datatable
        dynamicDataTable.Columns.Add(NameColumn);
        dynamicDataTable.Columns.Add(AddColumn);
        //loop for 5 item in DataTable
        for (int i = 0; i < 5; i++)
        {
            dynamicRow = dynamicDataTable.NewRow();
            //Add Rows to dymanicTable
            dynamicDataTable.Rows.Add(dynamicRow);
            //Assign Column value
            dynamicDataTable.Rows[i][NameColumn] = Guid.NewGuid().ToString();
            dynamicDataTable.Rows[i][AddColumn] = = Guid.NewGuid().ToString();
        }

        //Bind DynamicDataTable into a GridView
        GridViewDataShow.DataSource = dynamicDataTable;
       GridViewDataShow.DataBind();

Hope this code will help you
Regards,
Rajesh C#

0 comments: