Resources » Code Snippets » ASP.NET GridView

Dynamically adding columns to the GridView control


Last Updated:   Category: ASP.NET GridView    
Author: Member Level: Silver    Points: 8



With this code sample we can add columns to the GridView control at run time in ASP.NET. To successfully do so, follow the steps


1)define the column.


BoundField ID=NULL;
ID=new BoundField();
ID.HeaderText="ID";
ID.DataField="ID";
GridView1.Columns.Add(ID);

BoundField City=NULL;
City=new BoundField();
City.HeaderText="City";
City.DataField="City";
GridView1.Columns.Add(City);



2)define the datatable column


DataTable dt=new DataTable();
dt.Columns.Add(new DataColumn("ID",typeof(string)));
dt.Columns.Add(new DataColumn("City",typeof(string)));



3)define the DataRow


DataRow dr=dt.NewRow();
dr["ID"]="";
dr["City"]="";



4)Add DataRow into DataTable.


dt.Rows.Add(dr);



5)apply DataTable (dt) to the DataSource Property of GridView1


GridView1.DataSource=dt;



6) bind GridView


GridView1.DataBind();


Did you like this resource? Share it with your friends and show your love!

Responses to "Dynamically adding columns to the GridView control"

No responses found. Be the first to respond...

Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Priya jain
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India