After my last example with using web controls inside a repeater, I have a little more confidence in doing so. So much so, in fact, that this time I just jumped right in without thinking about it.
I'm building this little system for updating product data. These specific products have some basic properties (name, id, description), but they can also have some other properties. For instance, each product can be available in many colors, have multiple images (in thumbnail, regular, and large versions) and each one can have many sizes - with the price for the product based on the size. See below for a visual representation:
So the data representation is pretty simple: a products table and a sizes table(that contains all the sizes: an id field and a size field for each one) and a bridge table to join the two. In addition to the size id and the product id the bridge table also has a field for the price. Building the interface in ASP.NET for updating the two isn't as simple as the database implementation.
While I could have simply built a static form, I chose instead to dynamically build the form - a checkbox, size label, and a textbox for the price for each item in the size table. That was fairly simple to do with a repeater using a SQL statement that pulled from a view that listed all the product/sizes combinations and included the id field from the bridge table and price if the size was selected for the product. In the ItemDataBound event for the repeater I checked to see if the bridge table's id was greater than 0, if it was I set the checkbox as checked and filled in the price. Then I also set a viewstate item, the checkbox's unique id to the size's id field - so I could have it available later - when the submit button was clicked.
When the form is submitted I just delete all product/size combinations from the bridge table for the product and then recursively loop throught the controls of the repeater until I find a checkbox. If the checkbox is checked I pull the size id from the viewstate where I saved it earlier using the checkbox's unique id. I then grab the price value from the corresponding textbox (hint: since they are in the same item of the repeater, their unique id's are very similar). All that is needed then is to perform a SQL insert statement and then finish looping.