Search code examples
asp.netvb.netlistviewformviewitemtemplate

vb asp.net : A way to avoid repeating a code in common in ItemTemplate and EditItemTemplate


I'm a newbie in asp.net.

When using FormView, there is a big amount of code in ItemTemplate, EditItemTemplate and InsertItemTemplate which is almost identical.

For example:

<asp:ListBox ID="ListBox2" runat="server" Rows="1"  CssClass="field" 
   DataSourceID="StatusList" DataTextField="DESCRIPTION" 
 DataValueField="STAT_ID" SelectedValue='<%# Bind("STAT_ID") %>'>
</asp:ListBox>

(Note: at the exception that Eval() would be used instead of Bind() in ItemTemplate)

I've been trying to avoid repeating this code but without the expecting result:

  • ListView allows the use of LayoutTemplate - but I didn't see any examples that insert this kind of code in LayoutTemplate. And inserting this code in LayoutTemplate would result in an error.

  • DetailView allows to produce code automatically but I'd like to use a specific design (for ex. using "fieldset" that encompasses some fields).

What would be the best way to avoid repeating this kind of code ?


Solution

  • You don't have to much choice about seperately specifying the Bind/Eval part, but you do have some control over the other pieces. You can make a custom UserControl that contains your layout.

    Usually I include a property on this usercontrol called "Mode" which I either set to Edit or View, then based off of this property I change enabled/visible properties on the controls. You'll also need to include a property for each value you want bound/displayed in the usercontrol.

    Put some labels, textboxes, etc... in your designer and hook them up to properties in your code behind, put the usercontrol on your page in your item/edit template and eval/bind to your data to the various properties (make sure to set the mode so it displays right).