I’ve created a class library which exposes my back-end object model. I don’t wish to databind straight to SQL or XML, as a surprising number of tutorials/demos out there seem to assume.
In my Page_Load(), within the if (!IsPostbak), I currently set all the values of my controls from the object model, and call Databind() on each control.
I have a button event handler which deletes an item from the object model (it’s a List in this case) and rebinds it to the Repeater. First of all, this is messy – rebinding each time – but more importantly, no values are displayed when the page reloads. Should I put the databinding code outside the if statement in Page_Load()?
The second part of the question is regarding going back to basics – what’s the best way to databind in Asp.net? I’m mainly interested in binding against lists and arrays. I would have imagined there being a way to tell a control (e.g. TextBox) to databind to a string variable, and for the string to always reflect the contents of the text box, and the text box to always reflect the contents of the string. I tried the <%#…%> syntax but got no further than using the code-behind as described above.
I’ve read several overviews of databinding, but nothing out there seems to do what I want – they all talk about linking DataSets to a SQL database!
Turning to the knowledge of StackOverflow.
You’ll need to databind on every page load so you need to remove the code from within your !IsPostBack block.
When using a list or array handle the databinding event on the control. For a repeater you’ll need to handle the ItemDataBound event.
This example has been modified from http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx:
EDIT:
In addition, (and you may already be aware of this) you’ll need to persist your list/array somehow. You can go all the way back to the database and reconstitute the list there or you can store it in memory with cache, viewstate, or session as viable options depending on your needs.