views:

34

answers:

2

I have a database with 2 records Id and Description.

What I want to do is try to bind this to a table so for example

<tr>
   <drop down select list with ids available> <textbox>
</tr> <add button>

So the user can select an id from the drop down list, enter a description then click an add button next to this which will duplicate that block dynamically so they can enter as many as they like. What is the best way to go about this in webforms? Detailsview? I'm not sure how to make it dynamically add html blocks though? Any help would be appreciated.

A: 

pseudocode :

foreach description
    create new tablerow
    create a table cell in the row with the description as a label
    create a table cell in the row with the id dropdown as a combobox
    add the tablerow to the table.rows collection

the tricky part is accessing the data in your dynamically created table, but it shouldn't be hard to do as long as you set an identifier on each control that can be tied back to your data.

ZombieSheep
I wish I could do inline code like MVC, but this is webforms and I can't do code blocks inside a table :( unless its inside the <tr> itself
David
A: 

I'd stay away from any of the built in controls (i.e. DetailsView, FormView) for anything other than simple CRUD forms, as it's not much more effort to manually create your own data-entry forms.

Dynamically adding controls to an ASP.NET Webform (and have them work across postbacks) is quite a tricky one to get right, but in short you'll need to do something like:

  1. Add a table server control which will store your dynamic rows.
  2. Create a property (stored in ViewState or ControlState) to store a count of rows available.
  3. Handle the appropriate 'add' button click event, to increment the count property and add a new table row, and child controls.
  4. Inside an OnInit event, create the number of table rows stored in the count property.

Dynamically created controls aren't persisted across postbacks, so you'll need to create them on every postback during the pages OnInit method. As long as the controls are recreated in the right order and with the same ID's, then they will be repopulated successfully on postback.

Because you're dynamically adding controls, you may need to set the pages EnableEventValidation property to false.

richeym