Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

In Details Guide To DetailsView Control

DetailsView server control is used to display, delete, insert or edit a single record from data source. DetailsView control is often used in master/detail scenario with GridView control. To work with individual records in ASP.NET 1.1 you needed additional programming. But, in ASP.NET 2.0 or later we can use specialized DetailsView and FormView controls. More about FormView control you can read in FormView Control: Step by Step tutorial.

 

DetailsView control is located in Visual Studio toolbox, under Data tab.

DetailView control on toolbox

To start work with DetailsView control, grab control from the toolbox and place it on web form. By default, DetailsView control looks like in an image bellow:

DetailsView control on web form

To work with records, first we need to connect DetailsView control with some data source. In this example, I will use SqlDataSource control to bind DetailsView to SQl Server database. Here is a markup code for this SqlDataSource control:

<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>

This data source contains commands for all four basic operations: Select, Update, Insert and Delete. If you only need to show record in read-only mode, your data source control needs only Select command. After we created SqlDataSource control, we need to associate it with DetailsView control. You can do that in design view, like on next image:

Associate SqlDataSource control with DetailsView control.

Also, you can do this if you set DataSourceID property of DetailsView control to the name of your data source control.

To start an example, you need a database. SqlDataSource control above uses a database with Products and Categories tables. You can create these tables in your database with SQL code like this:

For table Products

CREATE TABLE Products(
[ID] [int] IDENTITY(1,1) NOT NULL,
[ProductName] [nvarchar](50) NOT NULL,
[Description] [nvarchar](250) NOT NULL,
[Image] [nvarchar](1000) NOT NULL,
[Category] [int] NOT NULL,
[ProductURL] [nvarchar](1000) NOT NULL
)

And, very simple table Categories

CREATE TABLE Categories(
[ID] [int] IDENTITY(1,1) NOT NULL,
[CategoryName] [nvarchar](50)
)

Fill tables with some data and run the example to see how it works. Of course, you can use your own existing table, just adopt SqlDataSource commands to suit your table structure. Run the example and DetailsView control will show first record, similar to the next image:

DetailsView control in read-only mode

How to update, insert and delete data and enable paging with DetailsView control

Until now, our example will only show one record in read-only mode. To enable paging, updating, deleting or adding new records, check proper checkboxes like in an image bellow:

Enabling paging, updating, inserting and deleting in DetailsView control

This action will produce markup code like this:

<asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="sdsForm" AllowPaging="True">
<Fields>
 <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>

Before using an example you need to set DataKeyNames property of DetailsView control to the name of table primary key column. In our case table primary key column is named "ProductID". Now, you can start an example again and joy in new features. Test paging, updating, deleting and inserting a new record to see how it works. You'll see new buttons Edit, Delete and New link buttons. Note that we did all this without writing single line of C# or VB.NET code! Output should look similar to image bellow:

DetailsView control with Edit, Delete and New link buttons and enabled paging

How to provide better layout with DetailsView control

Now, the example is completely functional, although it looks ugly. For example, instead of showing an URL of image, it would be better to show image itself, instead of product url it will be better to show clickable link etc.By default, DetailsView control has AutoGenerateRows property set to true. That means that all fields will be generated at run time, depending of what fields your data source contains. This is fast solution, but if you want more control over the way how fields will be presented, you need to set AutoGenerateRows property to False. Now you must specify needed fields manually. DetailsView control has seven types of fields, every with different purpose:

BoundField - This is default field, used when AutoGenerateRows is true. You can use it for simple text data type
ButtonField - Showing a Button control
CheckBoxField - Showing a CheckBox control, used for boolean yes/no fields
CommandField - Command buttons, like Edit, Delete or New, used for manipulating data
HyperLinkField - Used to show a hyperlink
ImageField - Used to show an image
TemplateField - Used to show data in custom layout, when other field types are inadequate

Implemented in our example, markup code with custom fields used could look like this:

<asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="sdsForm" Height="50px" Width="225px" AllowPaging="True" AutoGenerateRows="false">
<Fields>
 <%--Simple BoundField, we'll make it read-only --%>
 <asp:BoundField DataField="ProductID" ReadOnly="true" HeaderText="ID" />
 <%--TemplateField is used for ProductURL and ProductName fields--%>
 <asp:TemplateField HeaderText="Name">
  <ItemTemplate>
   <h1><a href='<%# Eval("ProductURL") %>'><%# Eval("ProductName") %></a></h1>
  </ItemTemplate>
  <EditItemTemplate>
   <table width="100%"><tr><td>
    Product name: </td><td><asp:TextBox ID="txtProductName" Text='<%# Bind("ProductName") %>' runat="server"></asp:TextBox></td></tr>
    <tr><td>Image URL: </td><td><asp:TextBox ID="txtImageURL" Text='<%#  Bind("ProductURL") %>' runat="server"></asp:TextBox></td></tr></table>
  </EditItemTemplate>
  <InsertItemTemplate>
   <table width="100%"><tr><td>
    Product name: </td><td><asp:TextBox ID="txtProductName" Text='<%# Bind("ProductName") %>' runat="server"></asp:TextBox></td></tr>
    <tr><td>Image URL: </td><td><asp:TextBox ID="txtImageURL" Text='<%#  Bind("ProductURL") %>' runat="server"></asp:TextBox></td></tr></table>
  </InsertItemTemplate>
 </asp:TemplateField>
 <asp:BoundField DataField="Description" HeaderText="Description" />
<%--This TemplateField show friendly category name from other table--%>
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
 <%# Eval("CategoryName") %>
</ItemTemplate>
<EditItemTemplate>
 <asp:DropDownList ID="ddlCategory"
  DataSourceID="sdsCategory"
  DataValueField="CategoryID"
  DataTextField="CategoryName"
  SelectedValue='<%#  Bind("Category") %>' runat="server" >
 </asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
 <asp:DropDownList ID="ddlCategory"
  DataSourceID="sdsCategory"
  DataValueField="CategoryID"
  DataTextField="CategoryName"
  SelectedValue='<%#  Bind("Category") %>' runat="server" >
 </asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
 <%--Image field is used to show product image--%>
 <asp:ImageField DataImageUrlField="Image" HeaderText="Image"></asp:ImageField>
 <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>

Category selection uses data from second table. To bind categories to DropDownList control we need to add another data source control. Markup for second SqlDataSource control looks like this (note that we need just SelectCommand here):

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

Output will now look like this:

DetailsView control with different field types

This layout looks definitely more user friendly. ImageField is used to show an image, primary key is presented as a read-only field and used TemplateField to enable advanced layout in product name and category selection. TemplateField is a little harder to use compared to other types of fields, but it allows almost unlimited formatting options. Practically, you can place complete all table columns in one TemplateField.

TemplateField contains ItemTemplate, EditItemTemplate and InsertItemTemplate sub tags used to specify different layouts for showing and editing of existing records or adding a new record. In ItemTemplate Eval() method is used since Bind() provides one direction read-only binding. For EditItemTemplate and InsertItemTemplate Bind() method is used. Bind() method enables binding in two directions.

Selection of category is presented in different layouts: as simple text in read-only mode and with DropDownList control in EditItemTemplate and InsertItemTemplate, so users can easily select category from offered category names in DropDownList, instead of writing of category ID to TextBox control.

DetailsView control layout when updating an existing record
DetailsView control layout when updating an existing record

Adding Header and Footer to get more professional look

To add Header and Footer elements to DetailsView control, use HeaderTemplate and FooterTemplate sub tags. Very simple imlementation of header and footer could look like this:

<HeaderTemplate>
My favorite products
</HeaderTemplate>
<FooterTemplate>
Copyright &copy; 2009, All rights reserved
</FooterTemplate>

Adding styles in DetailsView control

The easiest way to add professional formatting to DetailsView control is to use AutoFormat option. Click on AutoFormat... link button on DetailsView tasks or in Property window and choose one of few predefined styles. I'll choose Colorful auto format that will produce output like in next image:

DetailsView with AutoFormat used

If AutoFormat option can't satisfy your requirements, you can set styles of each element separately. DetailsView control has a number of style properties:

AlternatingRowStyle - Style of every alternate row
EditRowStyle - Style for the row in EditView, when you click to Edit command button control will use this style
RowStyle - Style of rows in display mode
PagerStyle - Defines style of pager (if pager is used, you can remove pager if you set AllowPaging property to false)
EmptyDataRowStyle - Style used if data source contains zero rows
HeaderStyle - Style used for header element
FooterStyle - Style used for footer element

Also, you can set things like background control image or table cell spacing by using properties from Appearance section.

Custom paging with DetailsView control

Default pager of DetailsView control contains numbers only. You can customize pager more by using PagerSettings property. You can try this line that shows only First, Previous, Next and Last buttons without numbers:

<PagerSettings Mode="NextPreviousFirstLast" NextPageText="&gt;" PreviousPageText="&lt;" LastPageText="&gt;&gt;" FirstPageText="&lt;&lt;" />

If existing pager modes are not enough for you, you can try with PagerTemplate to build your own pager layout, like this:

<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"  RunAt="server"/>   <asp:LinkButton ID="btnLast"  CommandName="Page" CommandArgument="Last"  Text="Last" RunAt="server"/>
</PagerTemplate>

If you need advanced options like optimized paging of large tables, search engine optimized (SEO) links in pager etc., you can consider our SEO Pager Control that solves limitations of all built-in ASP.NET pagers.

Conclusion

As you can see, DetailsView control can save you time in scenarios when you need to show, update, delete or add new record to data source. It is possible to build complete form for data manipulation without writing any C# or VB.NET code. You can see example used in this tutorial online at DetailsView control example, just without Edit, Insert and Delete buttons. You can list 5 records to see how it works.

There is a new FormView control that can be used in similar scenarios like DetailsView control. More about using of FormView control you can find in FormView Control: Step by step tutorial.


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