5 How will you fill the GridView by using DataTable object at runtime?

Answer

using System;
using System.Data;
public partial class Default : System.Web.UI.Page
{
           protected void Page_Load(object sender, EventArgs e)
           {
                     DataTable dt = new DataTable("Employee"); // Create the table object
                     DataColumn dc = new DataColumn();
                     DataRow dr;
                     dc.ColumnName = "ID"; //Heading of the coloumn
                     dc.DataType = Type.GetType("System.Int32"); //Set the type of ID as Integer
                     dt.Columns.Add(dc);
                     dc = new DataColumn();
                     dc.ColumnName = "ItemName";
                     dc.DataType = Type.GetType("System.String"); //Set the type of ItemName as String
                     dt.Columns.Add(dc); 
                     for (int i = 0; i <= 4; i++) //This code will create 5 new rows
                     {
                         dr = dt.NewRow(); 
                         dr["id"] = i;
                         dr["ItemName"] = "Item " + i;
                         dt.Rows.Add(dr);
                      }
                                 GridView1.DataSource = dt;
                                 GridView1.DataBind(); 
         }
}

Output of the above example:

All ado.net Questions

Ask your interview questions on ado-net

Write Your comment or Questions if you want the answers on ado-net from ado-net Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---