Partager via


How to: Customize Data Field Appearance and Behavior in a Dynamic Data Control

ASP.NET Dynamic Data uses field templates to render each data field of a table. Field templates are typically user controls (.ascx files) that are mapped to common language runtime (CLR) data types which are determined by the database data type. Usually, ASP.NET Dynamic Data provides one user control for displaying data of each type and another one for modifying or inserting data for that type.

This topic describes how to customize a data field appearance and behavior by setting the UIHint property in a Dynamic Data control such as the DynamicControl control and the DynamicField field. The UIHint property specifies what field template to use when a specific data field is rendered by one of these objects. The UIHint property can point to one of the provided templates or to a new one that you create. This approach is useful when you are not using pages that are automatically created by Dynamic Data, but instead you are creating custom Web pages to display and edit data.

Alternatively, you can change the display and appearance for the data field throughout the entire application by using attributes. For more information, see How to: Customize Data Field Appearance and Behavior in the Data Model.

To customize the appearance and behavior of a data field in a data-bound control

  1. Optionally, 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. If you are using the GridView or DetailsView controls, add a DynamicField object and set its UIHint property to the name of the field template to use to display the data.

    The following example shows how to use a DynamicField control to field 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.

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

    Note

    If the specified field template is not found, Dynamic Data uses a fallback mechanism. For more information, see ASP.NET Dynamic Data Field Templates Overview.

  3. If you are using data-bound controls that use templates or template fields, such as the ListView or the FormView controls, add a DynamicControl control to display the data, and set its UIHint property to the name of the data field to display.

    The following example specifies that the ProductName column will be rendered by using a field template named RedText when the item is in edit mode. At run time, Dynamic Data will search for a user control named RedText_Edit.ascx.

    <EditItemTemplate>
      <asp:DynamicControl runat="server"
        Mode="Edit"
        UIHint="RedText"
        DataField="ProductName" />
    </EditItemTemplate>
    

Example

The following example shows how to add the UIHint property to a DynamicField field of a GridView control. The property is set so that the data field uses a custom field template that displays a Calendar control for editing the discontinued 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="VB" %>

<script runat="server">

  Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs)
    DynamicDataManager1.RegisterControl(ProductsGridView)
  End Sub

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

          <!-- This example uses Microsoft SQL Server and connects   -->
          <!-- to the AdventureWorksLT sample database.              -->
          <asp:LinqDataSource ID="ProductsDataSource" runat="server" 
            EnableUpdate="true"
            TableName="Products" 
            ContextTypeName="AdventureWorksLTDataContext" />

          </ContentTemplate>
        </asp:UpdatePanel>

    </div>
  </form>
</body>
</html>
<%@ 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="VB" Inherits="System.Web.DynamicData.FieldTemplateUserControl" %>

<script runat="server">

  Function GetDateString() As String 
    If Not (FieldValue Is Nothing) Then
      Dim dt As DateTime = CType(FieldValue, DateTime)
      Return dt.ToShortDateString()
    Else
      Return String.Empty
    End If
  End Function
</script>

<%# GetDateString() %>
<%@ 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="VB" Inherits="System.Web.DynamicData.FieldTemplateUserControl" %>

<script runat="server">

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    TextBox1.ToolTip = Column.Description

    SetUpValidator(RequiredFieldValidator1)
    SetUpValidator(RegularExpressionValidator1)
    SetUpValidator(DynamicValidator1)
  End Sub

  Protected Overrides Sub ExtractValues(ByVal dictionary As IOrderedDictionary)
    dictionary(Column.Name) = ConvertEditedValue(TextBox1.Text)
  End Sub

  Public Overrides ReadOnly Property DataControl() As Control
    Get
      Return TextBox1
    End Get
  End Property

  Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    TextBox1.Text = Calendar1.SelectedDate.ToString("d")
  End Sub

  Function GetDateString() As String
    If Not (FieldValue Is Nothing) Then
      Dim dt As DateTime = CType(FieldValue, DateTime)
      Return dt.ToShortDateString()
    Else
      Return String.Empty
    End If
  End Function

</script>

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

<asp:Calendar ID="Calendar1" runat="server" 
  VisibleDate='<%# IIf(FieldValue Is Nothing, DateTime.Now, FieldValue) %>'
  SelectedDate='<%# IIf(FieldValue Is Nothing, DateTime.Now, FieldValue) %>' 
  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" />
<%@ 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" />

Compiling the Code

This example requires:

  • A Dynamic Data Web site or a Dynamic Data Web application.

  • Either the AdventureWorks or the AdventureWorksLT sample database. For information about how to download and install the SQL Server sample, see Microsoft SQL Server Product Samples: Database on the CodePlex site. Make sure that you install the correct version of the sample database for the version of SQL Server that you are running (SQL Server 2005 or SQL Server 2008).

  • A LINQ to SQL class configured to access the Products table of the AdventureWorks or AdventureWorksLT database.

  • A data context object that is registered to be used by Dynamic Data in the Global.asax file.

Robust Programming

The following conditions may cause an exception:

  • The database is unavailable.

See Also

Tasks

Walkthrough: Creating a New ASP.NET Dynamic Data Web Site Using Scaffolding

Concepts

ASP.NET Dynamic Data Overview

ASP.NET Dynamic Data Field Templates Overview

Reference

DynamicField.UIHint

DynamicControl.UIHint

Change History

Date

History

Reason

July 2008

Added topic for new feature.

SP1 feature change.