Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

FormView Control: Step by Step

FormView Control is introduced with ASP.NET 2.0. It is often used in master/details scenario with GridView, DataList or Repeater control. FormView Control is similar to DeatilsView control. Both controls enable showing of single record from data source. The main difference between FormView and DeatilsView controls is that FormView control allows using of templates for displaying a record instead of row fields used in DetailsView. Unlike DetailsView, FormView control doesn't have predefined data layout. Developer needs to create a template first and specify controls and formatting to display single record from data source. Because of that developer have full control over layout and it is pretty easy to add validation capabilities.

 

How to use FormView control

FormView control is by default located in Visual Studio toolbox, inside Data tab. If you place FormView control to web form you'll see that it not appears very user friendly at first look. There is only gray rectangle, like in image bellow:

FormView control placed on web form.

Unlike DetailsView control, there is no predefined template in FormView control. To show data, you need to select data source and create your own template to define control's appearance.

Binding FormView control to data source

There are two ways of data binding of FormView control: using of DataSourceID property or by using of DataSource property. Using fo DataSourceID property is recommended way because it enables easier paging and updating. When DataSourceID property is used, FormView control supports two way data binding, so in addition to showing the data, control will automatically support edit, insert and delete operations. Set FormView's DataSourceID property to the name of your data source control.

If your FormView control needs to show data in read-only mode only, set just SelectCommand property of data source control. If you also want to modify records, delete or add new items you need UpdateCommand, DeleteCommand and InsertCommand as well. Example of SqlDataSource control that will be used to select, insert, edit and delete data in FormView control could look like code bellow. This example shows typical situation where form includes Category field related to other table:

<asp:SqlDataSource ID="sdsForm" runat="server"
 ConnectionString="<%$ ConnectionStrings:ConnStr %>"
 InsertCommand="INSERT INTO Products(ProductName, Description, Image, Category, ProductURL) VALUES (@ProductName, @Description, @Image, @Category, @ProductURL)"
 SelectCommand="SELECT Products.ProductID, Products.ProductName, Products.Description, Products.Image, Products.ProductURL, Products.Category, Categories.CategoryName FROM Products INNER JOIN Categories ON Products.Category = Categories.ID ORDER BY ProductID"
 UpdateCommand="UPDATE Products SET ProductName = @ProductName, Description = @Description, Image = @Image, Category = @Category, ProductURL = @ProductURL WHERE ProductID = @ProductID"
 DeleteCommand="DELETE FROM Products WHERE ProductID = @ProductID">
   <UpdateParameters>
     <asp:Parameter Name="@ProductName" Type="String" />
     <asp:Parameter Name="@Description" Type="String" />
     <asp:Parameter Name="@Image" Type="String" />
     <asp:Parameter Name="@Category" Type="Int32" />
     <asp:Parameter Name="@ProductURL" Type="String" />         
   </UpdateParameters>
   <InsertParameters>
     <asp:Parameter Name="@ProductName" Type="String" />
     <asp:Parameter Name="@Description" Type="String" />
     <asp:Parameter Name="@Image" Type="String" />
     <asp:Parameter Name="@Category" Type="Int32" />
     <asp:Parameter Name="@ProductURL" Type="String" />             
   </InsertParameters>
</asp:SqlDataSource>

After you create your data source control, you need to associate data source name with DataSourceID property of FormView control. You can do it also in design view, like in image bellow.

Creating FormView control templates

FormView template consists from three parts: for viewing a record, edit a record, and add new record. Also, you can use it for browsing and deleting of records and include formatting for header and footer elements. Templates available in FormView controls are:

- HeaderTemplate
- ItemTemplate
- InsertItemTemplate
- EditItemTemplate
- EmptyDataTemplate
- PagerTemplate
- FooterTemplate

How to show data in FormView control

To show data in FormView control in read-only mode, we use ItemTemplate sub tag inside FormView tag, and Eval() method. If we set DataSourceID property to valid data source control, example code bellow will display ProductName and Description:

<ItemTemplate>
<h2><%# Eval("ProductName") %></h2>
<p><%# Eval("Description") %></p>
</
ItemTemplate>

Or, more common example with image, category and Edit/Insert/Delete link buttons, with confirmation message box for deleting a record:

<ItemTemplate>
 <h2><a href='<%# Eval("ProductURL") %>'><%# Eval("ProductName") %></a></h2>
 <p><%# Eval("Description") %></p>
 <a href='<%# Eval("ProductURL") %>'><img border="0" src='<%# Eval("Image") %>' alt='<%# Eval("ProductName") %>' /></a><br />
 <b>Category:</b> <%# Eval("CategoryName") %><br /><br />
 <asp:LinkButton ID="lbEdit" CausesValidation="false" CommandName="Edit" runat="server">Edit</asp:LinkButton>
 <asp:LinkButton ID="lbAddNew" CausesValidation="false" CommandName="New" runat="server">Add New Item</asp:LinkButton>
 <asp:LinkButton ID="lbDelete" CausesValidation="false" CommandName="Delete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this item?');">Delete</asp:LinkButton>
</ItemTemplate>

Also, with Eval method you can show formatted data. This syntax will format data as currency:

<%#Eval("Price","{0:c}")%>

How to edit, insert and delete data in FormView

To add new row to data source, use InsertItemTemplate. To edit existing row use EditItemTemplate. Unlike Eval() method in ItemTemplate example above, when insert or edit data you need Bind() method. Use Eval() method when you need read only data (binding in one direction, most used in ItemTemplate), and use Bind() method when you need binding in two directions, like in EditItemTemplate or InsertItemTemplate. Of course, you can disallow modification of some fields, and for read only fields use Label control and Eval() method.

Bellow is example of EditItemTemplate and InsertItemTemplate:

<EditItemTemplate>
 <table><tr><td>
 Product name: </td><td><asp:TextBox ID="txtProductName" Text='<%# Bind("ProductName") %>' runat="server"></asp:TextBox></td></tr>
  <tr><td>Description: </td><td><asp:TextBox ID="txtDescription" Text='<%# Bind("Description") %>' runat="server"></asp:TextBox></td></tr>
  <tr><td>Image URL: </td><td><asp:TextBox ID="txtImageURL" Text='<%# Bind("Image") %>' runat="server"></asp:TextBox></td></tr>
  <tr><td>Product URL: </td><td><asp:TextBox ID="txtProductURL" Text='<%# Bind("ProductURL") %>' runat="server"></asp:TextBox></td></tr>
  <tr><td>Category: </td><td><asp:DropDownList ID="ddlCategory"
   DataSourceID="sdsCategory"
   DataValueField="CategoryID"
   DataTextField="CategoryName"
   SelectedValue='<%# Bind("Category") %>' runat="server" >
   </asp:DropDownList></td></tr></table>
   <asp:LinkButton ID="lbSave" CommandName="Update" runat="server">Save</asp:LinkButton>
   <asp:LinkButton ID="lbCancel" CommandName="Cancel" runat="server">Cancel</asp:LinkButton>
</EditItemTemplate>
<InsertItemTemplate>
 <table border="0" width="100%">
  <tr><td>Product name: </td><td><asp:TextBox ID="txtProductName" Text='<%# Bind("ProductName") %>' runat="server"></asp:TextBox></td></tr>
  <tr><td>Description: </td><td><asp:TextBox ID="txtDescription" Text='<%# Bind("Description") %>' runat="server"></asp:TextBox></td></tr>
  <tr><td>Image URL: </td><td><asp:TextBox ID="txtImageURL" Text='<%# Bind("Image") %>' runat="server"></asp:TextBox></td></tr>
  <tr><td>Product URL: </td><td><asp:TextBox ID="txtProductURL" Text='<%# Bind("ProductURL") %>' runat="server"></asp:TextBox></td></tr>
  <tr><td>Category: </td><td><asp:DropDownList ID="ddlCategory"
   DataSourceID="sdsCategory"
   DataValueField="CategoryID"
   DataTextField="CategoryName"
   SelectedValue='<%# Bind("Category") %>' runat="server">
  </asp:DropDownList></td></tr></table>  
 <asp:LinkButton ID="lbSave" CommandName="Insert" runat="server">Save</asp:LinkButton>
 <asp:LinkButton ID="lbCancel" CommandName="Cancel" runat="server">Cancel</asp:LinkButton>
</InsertItemTemplate>

If Insert, Edit and Delete command buttons will be used, we need to set DataKeyNames property to the name of your table primary key (in our example SqlDataSource control, this field is ProductID).

When FormView control is initially displayed on web form, it will show ItemTemplate by default. You can change this behavior by using DefaultMode property, and show InsertItemTemplate or EditItemTemplate.

In case that your data source returned zero rows because you deleted all records or simply you didn't insert any record in table yet, FormView have nothing to show. In this case EmptyDataTemplate is shown. You can place any markup and style in this template, or just inform your user that there is no records in data source, like in example code bellow:

<EmptyDataTemplate>
There is no records in data source.
</EmptyDataTemplate>

Paging in FormView Control

To enable paging in FormView control, set AllowPaging property to true and default pager with numbers only will be displayed (if selected data source supports paging). If you are satisfied with good old paging with numbers only, you don't need to do anything else, FormView pager will work well.

If you want more control of layout, you can use PagerSettings property. By changing sub properties of PaggerSettings property, you can change pager look and feel according to your needs. This example will add First and Last buttons to default pager and limit number of visible pages to 5:

<PagerSettings Mode="NumericFirstLast" PageButtonCount="5" />

If you are still not satisfied with results, you can try PagerTemplate. PagerTemplate is used to create your own custom FormView pager.If PagerTemplate is used, default pager will not be shown. In template you can use any HTML tags, CSS or ASP.NET controls. Very simple example of PagerTemplate with four buttons is shown bellow:

<PagerTemplate>
<asp:LinkButton ID="btnFirst" CommandName="Page" CommandArgument="First" Text="First" RunAt="server"/>
 <asp:LinkButton ID="btnPrevious" CommandName="Page" CommandArgument="Prev"  Text="Previous" RunAt="server"/>
 <asp:LinkButton ID="btnNext" CommandName="Page" CommandArgument="Next"  Text="Next" nbsp;RunAt="server"/>
 <asp:LinkButton ID="btnLast" CommandName="Page" CommandArgument="Last"  Text="Last" RunAt="server"/>

</PagerTemplate>

If you need advanced features, like SEO friendly links, optimization for large tables etc., you can check our SEO Pager control.

DropDownList inside FormView control

Very often, used table contains column related with "one to many" relation to some column in other table in database. Typical example is selecting a category, where main table usually contains only foreign key, but user expects to select category name using DropDownList control, instead of writing a category id directly in TextBox control. To display category data we need second data source control. Create another data source that will contain CategoryName used for DataTextField property, and CategoryID field used for DataValueField property:

<asp:SqlDataSource ID="sdsCategory" runat="server" ConnectionString="<%$ ConnectionStrings:ConnStr %>" SelectCommand="SELECT ID AS CategoryID, CategoryName FROM Categories"></asp:SqlDataSource>

Set values of DataTextField and DataValueField properties and that is enough for inserting a new record in InsertItemTemplate. For EditItemTemplate, you can select current value from first data source with Bind() function. You can show categories in DropDownList by using markup code like this:

Category: <asp:DropDownList ID="ddlCategory"
DataSourceID="dsCategory"
DataTextField="CategoryName"
DataValueField="CategoryID"
SelectedValue='<%# Bind("Category") %>' runat="server" >
</asp:DropDownList>

How to define FormView control style

FormView control allows using of several self explaining sub tags, used to define style of each element. There are:

- <HeaderStyle />
- <RowStyle />
- <EditRowStyle />
- <InsertRowStyle />
- <EmptyDataRowStyle />
- <PagerStyle />
- <FooterStyle />

For example, to specify style of header and footer elements, we can use FormView sub tags like this:

<HeaderStyle BackColor="Blue" ForeColor="White" Font-Names="Arial" />
<FooterStyle BackColor="Khaki" ForeColor="DarkRed" Font-Names="Arial" />

If you use HeaderStyle and FooterStyle, then you need to show something in HeaderTemplate and FooterTemplate. This can be any markup code, including ASP.NET server controls. Here is example of pretty simple FormView header and footer that include plain text only:

<HeaderTemplate>
My favorite products
</HeaderTemplate>

<FooterTemplate>
FormView footer example
</FooterTemplate>

FormView control review

We came to the end of tutorial and I didn't write any C# or VB.NET code. FormView control is very customizable and you can make it functional just by using its templates and styles only without writing a single line of server side code. With use of text, markup and server side controls you can create impressive forms for data manipulation. In this tutorial, I presented common example of showing and editing a record that includes formatting, an image and selection of category. I hope you find it helpful.

Happy Programming!


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google