Tuesday, May 7, 2013

How to create datatable dynamically and Add new row in Datatable ASP.net C# VB

using System.Data.SqlClient;

 DataTable dt = new DataTable("HRT");  

 private void createTable()
        {
            DataColumn dc1 = new DataColumn("Sr", typeof(System.Int32));
            dc1.AutoIncrement = true;
            dc1.AutoIncrementSeed = 1;
            dc1.ReadOnly = true;
            dc1.Unique = true;
            dt.Columns.Add(dc1);

            DataColumn dc2 = new DataColumn("item1");
            dc2.DataType = System.Type.GetType("System.Int32");
            dt.Columns.Add(dc2);

            DataColumn dc3 = new DataColumn("PostPosition");
            dc3.DataType = System.Type.GetType("System.Int32");
            dt.Columns.Add(dc3);

            DataColumn dc4 = new DataColumn("Name");
            dc4.DataType = System.Type.GetType("System.String");
            dt.Columns.Add(dc4);
            DataColumn dc5 = new DataColumn("ClassName");
            dc5.DataType = System.Type.GetType("System.String");
            dt.Columns.Add(dc5);
            DataColumn dc6 = new DataColumn("Trainer");
            dc6.DataType = System.Type.GetType("System.String");
            dt.Columns.Add(dc6);
            DataColumn dc7 = new DataColumn("Score");
            dc7.DataType = System.Type.GetType("System.Decimal");
            dt.Columns.Add(dc7);
        }

Add new row in datatable
 DataRow dr1 = dt.NewRow();
                        dr1["item"] = Convert.ToString(ds.Tables[0].Rows[LIntCtr][2].ToString());
                        dr1["PostPosition"] = Convert.ToString(ds.Tables[0].Rows[LIntCtr][3].ToString());
                        dr1["Name"] = Convert.ToString(ds.Tables[0].Rows[LIntCtr][44].ToString());
                        dr1["ClassName"] = Convert.ToString(ds.Tables[0].Rows[LIntCtr][32].ToString());
                        dr1["Trainer"] = Convert.ToString(ds.Tables[0].Rows[LIntCtr][27].ToString());
                        dr1["Score"] = allValues;
                        dt.Rows.Add(dr1);