Thursday, September 07, 2006

Dynamically Adding Columns to GridView

I was asked in ASP.NET Forum why the dynamically inserted BoundField would be lost from the GridView's column collection on postback (eg. Button click in GridView)?

Many people would dynamically create controls in the Page_Load event. But I afraid it isn't a right place for the dynamic creation because the data in the control may not be pertained. (ViewState lost on postback). If possible, do the dynamic control creation in Initialization event (eg. Page_Init).

One of the differences between Page_Init and Page_Load is Page_Init event is only fired once and it is not fired on each postback, whereas the Page_Load event is always fired on every postback.

Back to the topic, hence, to avoid the dynamic GridView's fields gone from its GridView's collection on postback, you SHOULD always create it in GridView's Init event. For instance,

Protected Sub GridView_Init(sender as Object, e as EventArgs) Handles myGridView.Init
Dim field As New BoundField()
field.DataField = "data"

myGridView.Columns.Insert(0, field) 'To be first column in GridView
End Sub

The related discussion can be found here

Good luck !

1 comment:

ADmin said...

" Sitting and gazing at your exposition point custom essay writing services won't assist, however. You need to snatch a clear bit of paper.