In some complex scenarios developers
need to create runtime GridView dynamically. So obviously developers
need to create dynamic columns for dynamic gridviews. Here in this
article I will explain how one can develop or implement runtime
dynamically create bound column as well as template column of a GridView
control and also how to bind data into the dynamically created
GridView. For simplicity here i use a datatable but you can bind data
from database as well. Here I also showed how developers can write
dynamic event handler for dynamically created button within the template
column. The output will be:
Creating bound column is easier than
template column because if you want to add dynamic template column in
your GridView then you must implement ITemplate interface. When you
instantiate the implemented object then it will automatically call the
"InstantiateIn" method. To implement my example first add a class in
your project and named it "TemplateHandler". Then copy the code sample:
03 | using System.Web.UI.WebControls; |
05 | public class TemplateHandler : ITemplate |
07 | void ITemplate.InstantiateIn(Control container) |
09 | Button cmd= new Button(); |
12 | cmd.Click += new EventHandler(Dynamic_Method); |
13 | container.Controls.Add(cmd); |
16 | protected void Dynamic_Method( object sender, EventArgs e) |
18 | ((Button)sender).Text = "Hellooooo" ; |
Now add a page in your project & copy the below codes under page_load event:
01 | protected void Page_Load( object sender, EventArgs e) |
03 | DataTable dt = new DataTable(); |
05 | dt.Columns.Add( "FirstName" ); |
06 | dt.Columns.Add( "LastName" ); |
07 | dt.Columns.Add( "Age" , typeof (System.Int32)); |
09 | DataRow oItem = dt.NewRow(); |
10 | oItem[0] = "Shawpnendu" ; |
16 | oItem[0] = "Bimalendu" ; |
22 | GridView gv = new GridView(); |
23 | gv.AutoGenerateColumns = false ; |
25 | BoundField nameColumn = new BoundField(); |
26 | nameColumn.DataField = "FirstName" ; |
27 | nameColumn.HeaderText = "First Name" ; |
28 | gv.Columns.Add(nameColumn); |
30 | nameColumn = new BoundField(); |
31 | nameColumn.DataField = "LastName" ; |
32 | nameColumn.HeaderText = "Last Name" ; |
33 | gv.Columns.Add(nameColumn); |
35 | nameColumn = new BoundField(); |
36 | nameColumn.DataField = "Age" ; |
37 | nameColumn.HeaderText = "Age" ; |
38 | gv.Columns.Add(nameColumn); |
41 | TemplateField TmpCol = new TemplateField(); |
42 | TmpCol.HeaderText = "Click Me" ; |
43 | gv.Columns.Add(TmpCol); |
44 | TmpCol.ItemTemplate = new TemplateHandler(); |
49 | Form.Controls.Add(gv); |
Comments
Post a Comment