Dynamically adding columns to the GridView control

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();


Comments

No responses found. Be the first to 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:
    Email: