Adding template fields to grids dynamically

I want to populate a gridview and create a variable # of columns (templatefields containing textboxes) that are read in from a table.  I want to create the templatefields dynamically at runtime and create the onTextchanged events for each of these dynamically created textboxes to keep track of any changes made to this editable grid.  I read that dynamically created templatefields disappear during postbacks and have to be recreated on every postback.  
If the controls in the templatefields disappear on every postback, how would I setup the onTextchanged events for them?  Also, how would I preserve the data between postbacks?


Who is Participating?
gpfcall8Connect With a Mentor Author Commented:
I went with the fixed field solution.  I setup 20 template columns containing textboxes in a gridview and
set the datafield property to "1" for 1st col, "2" for 2nd col, etc...  On grid's rowdatabound event, I set the populate each gridview col textbox (1, 2, 3,...) with the corresponding col from the datatable.   Then in OnTextChanged event for each textbox, replaced the DataField #s with the actual data column names from the datatable.

Kumaraswamy RCommented:
gpfcall8Author Commented:
   The 3 links you provided do mention that the templatefields do disappear on postbacks and that they need to be recreated every time.  But again, if they are recreated, how can the data be preserved between postbacks and how to setup/capture the dynamic controls' onTextchanged events to update this data?  

  Instead of going into this minefield of creating the fields dynamically, I was thinking of setting up the gridview with a maximum (say 20) fixed number of columns/templatefields containing textboxes with no datafield attributes defined until the page loads and then set the datafields of a subset of them to actual data columnnames from my query. (and hide the remaining blank columns) But I am having trouble figuring out how to access the textbox controls in the dynamic templatefields.  I think it would need to be done before row_databound event of the gridview (gridDataBinding event or form_load??)  Anyone know how to access the templatefield controls then?  I think they are hidden on purpose for security reasons?


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.