few days back i spent alot of my time in googling about bindable controls creation on runtime but whatever tutorial/article i follow fail me to achieve my purpose mostly at 99% which makes me crazy coz this doesn’t happen with me only 1 or 2 times so i decided then when i will achieve this functionality i will must write blog about it and solution as well
finally today i ‘d like to talk about dynamically controls creation in asp.net which i found quite easy but for newbie it become quite hectic because to create control at runtime is not an issue but to persist them after post back is an issue even u keep their EnableViewState property true , solution is quite simple but that depends upon scenario/need. if you need to create such controls e.g, gridview, datalist, repeater,.. which need to bind then simply follow following steps:
- create controls in Page_Init event
- bind controls in Page_Load event
thats it its a matter of two steps but drive you nuts if you don’t know coz those controls which created on Page_Init doesn’t persist after postback if you just create them in Page_Load and in Not Postback condition coz it will be created once when first time page loads afterwards it wont be created so u wont be able to see it again but if u don’t put Not Postback condition then everytime it willl be create suppose if you create edittable grid (or any control) and u edit something and press update button next time but on page_load event it will create all controls again and somehow bind as well if u r binding then ur modifications wont remain anymore so …………… :s that was just a 1 scenario so if you bind again and again your modification wont persist and if you don’t create control again and again on each postback ur controls wont persist
so the solution is to create controls in Page_Init event without putting condition of Not postback and bind your controls in Page_Load event under condition of Not Postback …
few solutions i would like to write which are somehow out of the scope of this article but you might get whilst working on asp.net binding controls …..
sometime when we want to bubble event means we use datalist and in datalist we put button and button will fire event of datalist which can be capture in Item_Command event of that datalist, WONT BE FIRE if you write databinding code of datalist in Page_Load event without or out of condition of Not Postback so keep your databinding code under Page not postback condition.
you can’t rebind your code from bubble event means if you have any button/linkbutton/image button or any such control which cause postback and fire event of datalist don’t try to rebind your datalist in it .. coz it wont happen from there
may be some time you found problem of getting some events fired twice it happens when your AutoEventWireUp = true so keep it false (good practice)
i will post couple of sample code very soon or you may post comment with your email id to get sample codes via email