How to: Add Dynamic Behavior to Data-Bound Controls

This topic describes how to add Dynamic Data behavior to the GridView, and DetailsView, ListView, and FormView controls.

Dynamic Data behavior lets you customize a data field appearance and behavior by setting attributes on properties in the data model or by setting the UIHint property in a DynamicControl or DynamicField control. This topic shows how to use the UIHint property. For information about how to use attributes in the data model, see . Using Dynamic Data Functionality to Format and Validate Data on the ASP.NET web site.

In order to add dynamic behavior to one of these controls, you must have the following in your web project:

A Visual Studio project with source code is available to accompany this topic: Adding Dynamic Data.

To add dynamic behavior to a GridView or DetailsView control

  1. In Visual Studio or Visual Web Developer Express, open the Web site.

  2. Open the ASP.NET Web page that contains the EntityDataSource control or the LinqDataSource control.

  3. Add a GridView or DetailsView control to the page.

  4. Add a DynamicDataManager control to the page.

  5. Set the ControlID property of the DataControlReference element in the DynamicDataManager control to the ID of the GridView or DetailsView control.

    This registers the data-bound control and enables dynamic behavior for it.

  6. Set the DataSourceID property of the GridView or DetailsView control to the ID of the EntityDataSource control or the LinqDataSource control.

  7. Set the AutoGenerateColumns property of the GridView control or the AutoGenerateRows property of the DetailsView control to false.

  8. For each column in the GridView control or row in the DetailsView control that you want to enable Dynamic Data behavior for, do the following:

    1. Add a DynamicField control.

    2. Set the DataField property of the DynamicField control to the name of the data column or row that you want to bind to.

To add dynamic behavior to a ListView or FormView control

  1. In Visual Studio or Visual Web Developer Express, open the Web site that you want to add Dynamic Data behavior to.

  2. Open an ASP.NET Web page that contains an EntityDataSource control or the LinqDataSource control.

  3. Add a ListView or FormView control to the page.

  4. Add a DynamicDataManager control to the page.

  5. Set the ControlID property of the DataControlReference element in the DynamicDataManager control to the ID of the ListView or FormView control.

    This registers the data-bound control and enables dynamic behavior for it.

  6. Set the DataSourceID property of the ListView or FormView control to the ID of the EntityDataSource control or the LinqDataSource control.

  7. For each column in the ListView control or row in the FormView control that you want to enable data field display for, do the following:

    1. Add a DynamicControl control to the ItemTemplate template of the data-bound control.

    2. Set the DataField property of the DynamicControl control to the name of the data column or row that you want to bind to.

  8. For each column in the ListView control or row in the FormView control that you want to enable data field editing for, do the following:

    1. Add a DynamicControl control to the EditItemTemplate template of the data-bound control.

    2. Set the DataField property of the DynamicControl control to the name of the data column or row that you want to bind to.

    3. Set the Mode property to the Edit.

To customize the appearance and behavior of a data field

  1. Create a custom field template that defines the UI for a specific data field in the data model. For more information, see How to: Customize Data Field Display in the Data Model

  2. Set the DynamicField.UIHint or DynamicControl.UIHintproperty to the name of the field template to use to display the data.

    The following example shows how to use a DynamicField control to render the ProductName column by using a field template named RedText. In display mode, the data is displayed by using a field template named RedText.ascx. In edit or insert mode, the data is displayed by using a field template named RedText_Edit.ascx or RedText_Insert.ascx.

    <asp:DynamicField
      UIHint="RedText"
      DataField="ProductName" />
    
    NoteNote

    If the specified field template is not found, Dynamic Data displays the default template based on the data type.

The following example shows pages that add Dynamic Data behavior to the GridView, DetailsView, ListView, and FormView controls.

<asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource" 
    EnablePersistedSelection="True" AutoGenerateColumns="False" GridLines="None" 
    AllowPaging="True" AllowSorting="True" CssClass="DDGridView"
    RowStyle-CssClass="td" HeaderStyle-CssClass="th" CellPadding="6">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:DynamicHyperLink runat="server" Action="Edit" Text="Edit"
                />&nbsp;<asp:LinkButton runat="server" CommandName="Delete" Text="Delete"
                    OnClientClick='return confirm("Are you sure you want to delete this item?");'
                />&nbsp;<asp:DynamicHyperLink runat="server" Text="Details" /> 

            </ItemTemplate>
        </asp:TemplateField>

        <asp:DynamicField DataField="OrderQty" HeaderText="Order Quantity" />
        <asp:DynamicField DataField="UnitPrice" HeaderText="Unit Price" />
        <asp:DynamicField DataField="ModifiedDate" HeaderText="Modified Date" />
        <asp:DynamicField DataField="SalesOrderHeader" HeaderText="Sales Order" />
        <asp:DynamicField DataField="Product" HeaderText="Product Name" />
    </Columns>
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle CssClass="th" />

    <PagerStyle CssClass="DDFooter"/>        
    <PagerTemplate>
        <asp:GridViewPager runat="server" />
    </PagerTemplate>
    <EmptyDataTemplate>
        There are currently no items in this table.
    </EmptyDataTemplate>
    <RowStyle CssClass="td" />
</asp:GridView>
<asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" 
    CssClass="DDDetailsTable"
    AutoGenerateRows="False" DataSourceID="GridDataSource">

    <Fields>
        <asp:DynamicField DataField="OrderQty" HeaderText="Order Quantity" />
        <asp:DynamicField DataField="UnitPrice" HeaderText="Unit Price" />
        <asp:DynamicField DataField="ModifiedDate" HeaderText="Modified Date" />
        <asp:DynamicField DataField="Product" HeaderText="Product" />

        <asp:TemplateField ShowHeader="False" >
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit" Text="Edit" /> &nbsp;
                <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete"
                    OnClientClick='return confirm("Are you sure you want to delete this item?");' />
            </ItemTemplate>

            <EditItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" 
                    CommandName="Update" Text="Update"></asp:LinkButton> &nbsp;
                <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" 
                    CommandName="Cancel" Text="Cancel"></asp:LinkButton>
            </EditItemTemplate>
        </asp:TemplateField>

    </Fields>

</asp:DetailsView>
        <asp:ListView ID="ListView1" runat="server" DataKeyNames="CustomerID"  
            DataSourceID="EntityDataSource1">

            <EditItemTemplate>
                <tr style="">
                    <td>
                        <asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" 
                         CausesValidation="true" Text="Update" />
                        <asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel"  
                        CausesValidation="false" Text="Cancel" />
                    </td>


                    <td>
                        <asp:DynamicControl runat="server" DataField="FirstName" Mode="Edit" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="LastName" Mode="Edit" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="CompanyName" Mode="Edit" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="EmailAddress" Mode="Edit" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="ModifiedDate" Mode="Edit" />
                    </td>

                </tr>
            </EditItemTemplate>
            <EmptyDataTemplate>
                <table runat="server" style="">
                    <tr>
                        <td>
                            No data was returned.</td>
                    </tr>
                </table>
            </EmptyDataTemplate>

            <ItemTemplate>
                <tr style="">
                    <td>

                        <asp:LinkButton ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
                        <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete"
                            OnClientClick='return confirm("Are you sure you want to delete this item?");' />

                    </td>


                    <td>
                        <asp:DynamicControl runat="server" DataField="FirstName" Mode="ReadOnly" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="LastName" Mode="ReadOnly" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="CompanyName" Mode="ReadOnly" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="EmailAddress" Mode="ReadOnly" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="ModifiedDate" Mode="ReadOnly" />
                    </td>

                </tr>
            </ItemTemplate>
            <LayoutTemplate>
                <table  class="ExampleView" runat="server">
                    <tr runat="server">
                        <td runat="server">
                            <table ID="itemPlaceholderContainer" runat="server" border="0" style="">
                                <tr runat="server" style="">
                                    <th runat="server">
                                    </th>

                                    <th runat="server">
                                        FirstName</th>

                                    <th runat="server">
                                        LastName</th>

                                    <th runat="server">
                                        CompanyName</th>

                                    <th runat="server">
                                        EmailAddress</th>

                                    <th runat="server">
                                        ModifiedDate</th>

                                </tr>
                                <tr ID="itemPlaceholder" runat="server">
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr runat="server">
                        <td runat="server" style="">
                            <asp:DataPager ID="DataPager1" runat="server">
                                <Fields>
                                    <asp:NumericPagerField />
                                </Fields>
                            </asp:DataPager>
                        </td>
                    </tr>
                </table>
            </LayoutTemplate>
            <SelectedItemTemplate>
                <tr style="">
                    <td>

                        <asp:LinkButton ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
                        <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete"
                            OnClientClick='return confirm("Are you sure you want to delete this item?");' />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="FirstName" Mode="ReadOnly" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="LastName" Mode="ReadOnly" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="CompanyName" Mode="ReadOnly" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="EmailAddress" Mode="ReadOnly" />
                    </td>

                    <td>
                        <asp:DynamicControl runat="server" DataField="ModifiedDate" Mode="ReadOnly" />
                    </td>


                </tr>
            </SelectedItemTemplate>
        </asp:ListView>
              <asp:FormView ID="FormViewId" runat="server" AllowPaging="True"  CssClass="DDDetailsTable"
                  DataSourceID="EntityDataSource1">
                  <EditItemTemplate>
                      FirstName:
                      <asp:DynamicControl ID="FirstNameDynamicControl" runat="server" 
                          DataField="FirstName" Mode="Edit" />
                      <br />
                      LastName:
                      <asp:DynamicControl ID="LastNameDynamicControl" runat="server" 
                          DataField="LastName" Mode="Edit" />
                      <br />
                      CompanyName:
                      <asp:DynamicControl ID="CompanyNameDynamicControl" runat="server" 
                          DataField="CompanyName" Mode="Edit" />
                      <br />
                      EmailAddress:
                      <asp:DynamicControl ID="EmailAddressDynamicControl" runat="server" 
                          DataField="EmailAddress" Mode="Edit" />
                      <br />
                      ModifiedDate:
                      <asp:DynamicControl ID="ModifiedDateDynamicControl" runat="server" 
                          DataField="ModifiedDate" Mode="Edit" />
                      <br />
                      <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" 
                          CommandName="Update" Text="Update" />
                      &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" 
                          CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                  </EditItemTemplate>

                  <ItemTemplate>
                  <table  class="DDDetailsTable">
                    <tr> 
                        <td> FirstName:</td>
                        <td> <asp:DynamicControl ID="FirstNameDynamicControl" runat="server" 
                          DataField="FirstName" /></td> 
                    </tr>

                    <tr>
                        <td> LastName: </td>
                        <td> <asp:DynamicControl ID="LastNameDynamicControl" runat="server" 
                          DataField="LastName" /></td>
                    </tr>                
                    <tr>
                        <td> Company Name: </td>
                        <td> <asp:DynamicControl ID="CompanyNameDynamicControl" runat="server" 
                          DataField="CompanyName" /> </td>
                    </tr>
                    <tr>
                        <td>EmailAddress:</td>
                        <td><asp:DynamicControl ID="EmailAddressDynamicControl" runat="server" 
                            DataField="EmailAddress" /></td>
                    </tr>
                    <tr>
                        <td> Modified Date:</td>
                        <td><asp:DynamicControl ID="ModifiedDateDynamicControl4" runat="server" 
                          DataField="ModifiedDate" /></td>
                    </tr>

                  </table>

                  <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit" Text="Edit" /> &nbsp;
                  <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete"
                    OnClientClick='return confirm("Are you sure you want to delete this item?");' />

                  </ItemTemplate>

              </asp:FormView>

The following example shows how to add the UIHint property to a DynamicField control in a GridView control. The property is set so that the data field uses a custom field template that displays a Calendar control for editing a date. The second and third examples show the user control code for the field templates that define the UI to display the date in short format and to edit the field.

<%@ Page Language="C#" %>

<script runat="server">

  protected void Page_Init(object sender, EventArgs e) 
  {
    DynamicDataManager1.RegisterControl(ProductsGridView);
  }

</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>UIHint Property Sample</title>
    <link href="~/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>

  <form id="form1" runat="server">
    <div>
      <h2><%= ProductsDataSource.TableName%> table</h2>

      <asp:DynamicDataManager ID="DynamicDataManager1" runat="server"
        AutoLoadForeignKeys="true" />

      <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"/>

      <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>        

          <asp:GridView ID="ProductsGridView" runat="server" DataSourceID="ProductsDataSource"
            AutoGenerateEditButton="true"
            AutoGenerateColumns="false"
            AllowSorting="true"
            AllowPaging="true">
            <Columns>
              <asp:DynamicField DataField="Name" />
              <asp:DynamicField DataField="ProductNumber" />
              <asp:DynamicField DataField="DiscontinuedDate" UIHint="DateCalendar" />
            </Columns>        
            <EmptyDataTemplate>
              There are currently no items in this table.
            </EmptyDataTemplate>
          </asp:GridView>

          <asp:LinqDataSource ID="ProductsDataSource" runat="server" 
            EnableUpdate="true"
            TableName="Products" 
            ContextTypeName="AdventureWorksLTDataContext" />

          </ContentTemplate>
        </asp:UpdatePanel>

    </div>
  </form>
</body>
</html>
<%@ Control Language="C#" Inherits="System.Web.DynamicData.FieldTemplateUserControl" %>

<script runat="server">
    string GetDateString() 
    {
      if (FieldValue != null)
      {
        DateTime dt = (DateTime)FieldValue;
        return dt.ToShortDateString();
      }
      else
      {
        return string.Empty;
      }
    }
</script>

<%# GetDateString() %>
<%@ Control Language="C#" Inherits="System.Web.DynamicData.FieldTemplateUserControl" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e) {
        TextBox1.ToolTip = Column.Description;

        SetUpValidator(RequiredFieldValidator1);
        SetUpValidator(RegularExpressionValidator1);
        SetUpValidator(DynamicValidator1);
    }

    protected override void ExtractValues(IOrderedDictionary dictionary) {
      dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);
    }

    public override Control DataControl
    {
      get
      {
        return TextBox1;
      }
    }  

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
      TextBox1.Text = Calendar1.SelectedDate.ToString("d");
    }

    string GetDateString()
    {
      if (FieldValue != null)
      {
        DateTime dt = (DateTime)FieldValue;
        return dt.ToShortDateString();
      }
      else
      {
        return string.Empty;
      }
    }
</script>

<asp:TextBox ID="TextBox1" runat="server" 
  Text='<%# GetDateString() %>' 
  MaxLength="10">
</asp:TextBox>

<asp:Calendar ID="Calendar1" runat="server" 
  VisibleDate='<%# (FieldValue != null) ? FieldValue : DateTime.Now %>'
  SelectedDate='<%# (FieldValue != null) ? FieldValue : DateTime.Now %>'
  OnSelectionChanged="Calendar1_SelectionChanged" />

<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" 
  CssClass="droplist" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />
<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1" 
  CssClass="droplist" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />  
<asp:DynamicValidator runat="server" ID="DynamicValidator1" 
  CssClass="droplist" ControlToValidate="TextBox1" Display="Dynamic" />

The examples require the following:

Show: