FormView Class

Definition

Displays the values of a single record from a data source using user-defined templates. The FormView control allows you to edit, delete, and insert records.

public ref class FormView : System::Web::UI::WebControls::CompositeDataBoundControl, System::Web::UI::IDataItemContainer, System::Web::UI::IPostBackEventHandler, System::Web::UI::WebControls::IPostBackContainer
public ref class FormView : System::Web::UI::WebControls::CompositeDataBoundControl, System::Web::UI::IDataItemContainer, System::Web::UI::IPostBackEventHandler, System::Web::UI::WebControls::IDataBoundItemControl, System::Web::UI::WebControls::IPostBackContainer
[System.Web.UI.ControlValueProperty("SelectedValue")]
public class FormView : System.Web.UI.WebControls.CompositeDataBoundControl, System.Web.UI.IDataItemContainer, System.Web.UI.IPostBackEventHandler, System.Web.UI.WebControls.IPostBackContainer
[System.Web.UI.ControlValueProperty("SelectedValue")]
public class FormView : System.Web.UI.WebControls.CompositeDataBoundControl, System.Web.UI.IDataItemContainer, System.Web.UI.IPostBackEventHandler, System.Web.UI.WebControls.IDataBoundItemControl, System.Web.UI.WebControls.IPostBackContainer
[<System.Web.UI.ControlValueProperty("SelectedValue")>]
type FormView = class
    inherit CompositeDataBoundControl
    interface IDataItemContainer
    interface INamingContainer
    interface IPostBackEventHandler
    interface IPostBackContainer
[<System.Web.UI.ControlValueProperty("SelectedValue")>]
type FormView = class
    inherit CompositeDataBoundControl
    interface IDataItemContainer
    interface INamingContainer
    interface IPostBackEventHandler
    interface IPostBackContainer
    interface IDataBoundItemControl
    interface IDataBoundControl
Public Class FormView
Inherits CompositeDataBoundControl
Implements IDataItemContainer, IPostBackContainer, IPostBackEventHandler
Public Class FormView
Inherits CompositeDataBoundControl
Implements IDataBoundItemControl, IDataItemContainer, IPostBackContainer, IPostBackEventHandler
Inheritance
Attributes
Implements

Examples

The following example demonstrates how to use a FormView control to display the values from a SqlDataSource control.


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

<!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 runat="server">
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>FormView Example</h3>
                       
      <asp:formview id="EmployeeFormView"
        datasourceid="EmployeeSource"
        allowpaging="true"
        datakeynames="EmployeeID" 
        runat="server">
        
        <itemtemplate>
        
          <table>
            <tr>
              <td>
                <asp:image id="EmployeeImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td>
                <h3><%# Eval("FirstName") %> <%# Eval("LastName") %></h3>      
                <%# Eval("Title") %>        
              </td>
            </tr>
          </table>
        
        </itemtemplate>
          
        <pagersettings position="Bottom"
          mode="NextPrevious"/> 
                  
      </asp:formview>
          
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="EmployeeSource"
        selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [PhotoPath] From [Employees]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

<%@ Page language="VB" %>

<!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 runat="server">
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>FormView Example</h3>
                       
      <asp:formview id="EmployeeFormView"
        datasourceid="EmployeeSource"
        allowpaging="true"
        datakeynames="EmployeeID" 
        runat="server">
        
        <itemtemplate>
        
          <table>
            <tr>
              <td>
                <asp:image id="EmployeeImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td>
                <h3><%# Eval("FirstName") %> <%# Eval("LastName") %></h3>      
                <%# Eval("Title") %>        
              </td>
            </tr>
          </table>
        
        </itemtemplate>
          
        <pagersettings position="Bottom"
          mode="NextPrevious"/> 
                  
      </asp:formview>
          
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="EmployeeSource"
        selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [PhotoPath] From [Employees]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

The following example demonstrates how to use a FormView control to edit existing records.

Important

The control in this example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.


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

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

  void EmployeeFormView_ItemUpdating(Object sender, FormViewUpdateEventArgs e)
  {

    // Validate the field values entered by the user. This
    // example determines whether the user left any fields
    // empty. Use the NewValues property to access the new 
    // values entered by the user.
    ArrayList emptyFieldList = ValidateFields(e.NewValues);

    if (emptyFieldList.Count > 0)
    {

      // The user left some fields empty. Display an error message.
      
      // Use the Keys property to retrieve the key field value.
      String keyValue = e.Keys["EmployeeID"].ToString();

      MessageLabel.Text = "You must enter a value for each field of record " +
        keyValue + ".<br/>The following fields are missing:<br/><br/>";

      // Display the missing fields.
      foreach (String value in emptyFieldList)
      {
        // Use the OldValues property to access the original value
        // of a field.
        MessageLabel.Text += value + " - Original Value = " + 
          e.OldValues[value].ToString() + "<br />";
      }

      // Cancel the update operation.
      e.Cancel = true;

    }
    else
    {
      // The field values passed validation. Clear the
      // error message label.
      MessageLabel.Text = "";
    }

  }

  ArrayList ValidateFields(IOrderedDictionary list)
  {
    
    // Create an ArrayList object to store the
    // names of any empty fields.
    ArrayList emptyFieldList = new ArrayList();

    // Iterate though the field values entered by
    // the user and check for an empty field. Empty
    // fields contain a null value.
    foreach (DictionaryEntry entry in list)
    {
      if (entry.Value == String.Empty)
      {
        // Add the field name to the ArrayList object.
        emptyFieldList.Add(entry.Key.ToString());
      }
    }

    return emptyFieldList;
  }

  void EmployeeFormView_ModeChanging(Object sender, FormViewModeEventArgs e)
  {
    if (e.CancelingEdit)
    {
      // The user canceled the update operation.
      // Clear the error message label.
      MessageLabel.Text = "";
    }
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>FormView Example</h3>
                       
      <asp:formview id="EmployeeFormView"
        datasourceid="EmployeeSource"
        allowpaging="true"
        datakeynames="EmployeeID"
        headertext="Employee Record"
        emptydatatext="No employees found."
        onitemupdating="EmployeeFormView_ItemUpdating"
        onmodechanging="EmployeeFormView_ModeChanging"  
        runat="server">
        
        <headerstyle backcolor="CornFlowerBlue"
          forecolor="White"
          font-size="14"
          horizontalalign="Center"  
          wrap="false"/>
        <rowstyle backcolor="LightBlue"
          wrap="false"/>
        <pagerstyle backcolor="CornFlowerBlue"/>

        <itemtemplate>
          <table>
            <tr>
              <td rowspan="6">
                <asp:image id="EmployeeImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <%# Eval("FirstName") %> <%# Eval("LastName") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <%# Eval("Title") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Hire Date:</b>                 
              </td>
              <td>
                <%# Eval("HireDate","{0:d}") %>
              </td>
            </tr>
            <tr style="height:150; vertical-align:top">
              <td>
                <b>Address:</b>
              </td>
              <td>
                <%# Eval("Address") %><br/>
                <%# Eval("City") %> <%# Eval("Region") %>
                <%# Eval("PostalCode") %><br/>
                <%# Eval("Country") %>   
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="Edit"
                  text="Edit"
                  commandname="Edit"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </itemtemplate>
        <edititemtemplate>
          <table>
            <tr>
              <td rowspan="6">
                <asp:image id="EmployeeEditImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <asp:textbox id="FirstNameUpdateTextBox"
                  text='<%# Bind("FirstName") %>'
                  runat="server"/>
                <asp:textbox id="LastNameUpdateTextBox"
                  text='<%# Bind("LastName") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <asp:textbox id="TitleUpdateTextBox"
                  text='<%# Bind("Title") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td>
                <b>Hire Date:</b>                 
              </td>
              <td>
                <asp:textbox id="HireDateUpdateTextBox"
                  text='<%# Bind("HireDate", "{0:d}") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr style="height:150; vertical-align:top">
              <td>
                <b>Address:</b>
              </td>
              <td>
                <asp:textbox id="AddressUpdateTextBox"
                  text='<%# Bind("Address") %>'
                  runat="server"/>
                <br/>
                <asp:textbox id="CityUpdateTextBox"
                  text='<%# Bind("City") %>'
                  runat="server"/> 
                <asp:textbox id="RegionUpdateTextBox"
                  text='<%# Bind("Region") %>'
                  width="40"
                  runat="server"/>
                <asp:textbox id="PostalCodeUpdateTextBox"
                  text='<%# Bind("PostalCode") %>'
                  width="60"
                  runat="server"/>
                <br/>
                <asp:textbox id="CountryUpdateTextBox"
                  text='<%# Bind("Country") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="UpdateButton"
                  text="Update"
                  commandname="Update"
                  runat="server"/>
                <asp:linkbutton id="CancelButton"
                  text="Cancel"
                  commandname="Cancel"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </edititemtemplate>
          
        <pagersettings position="Bottom"
          mode="Numeric"/> 
                  
      </asp:formview>
      
      <br/><br/>
      
      <asp:label id="MessageLabel"
          forecolor="Red"
          runat="server"/>
          
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="EmployeeSource"
        selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [Address], [City], [Region], [PostalCode], [Country], [HireDate], [PhotoPath] From [Employees]"
        updatecommand="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName, [Title]=@Title, [Address]=@Address, [City]=@City, [Region]=@Region, [PostalCode]=@PostalCode, [Country]=@Country Where [EmployeeID]=@EmployeeID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

<%@ Page language="VB" %>

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

  Sub EmployeeFormView_ItemUpdating(ByVal sender As Object, ByVal e As FormViewUpdateEventArgs) Handles EmployeeFormView.ItemUpdating
  
    ' Validate the field values entered by the user. This
    ' example determines whether the user left any fields
    ' empty. Use the NewValues property to access the new 
    ' values entered by the user.
        Dim emptyFieldList As ArrayList = ValidateFields(e.NewValues)

    If emptyFieldList.Count > 0 Then

      ' The user left some fields empty. Display an error message.
      
      ' Use the Keys property to retrieve the key field value.
      Dim keyValue As String = e.Keys("EmployeeID").ToString()

      MessageLabel.Text = "You must enter a value for each field of record " & _
        keyValue & ".<br/>The following fields are missing:<br/><br/>"

      ' Display the missing fields.
      Dim value As String
      For Each value In emptyFieldList
      
        ' Use the OldValues property to access the original value
        ' of a field.
        MessageLabel.Text &= value & " - Original Value = " & _
          e.OldValues(value).ToString() & "<br />"
        
      Next

      ' Cancel the update operation.
      e.Cancel = True

    Else
    
      ' The field values passed validation. Clear the
      ' error message label.
      MessageLabel.Text = ""
      
    End If

  End Sub

  Function ValidateFields(ByVal list As IOrderedDictionary) As ArrayList
    
    ' Create an ArrayList object to store the
    ' names of any empty fields.
    Dim emptyFieldList As New ArrayList()

    ' Iterate though the field values entered by
    ' the user and check for an empty field. Empty
    ' fields contain a null value.
    Dim entry As DictionaryEntry
    
    For Each entry In list
    
      If entry.Value Is String.Empty Then
      
        ' Add the field name to the ArrayList object.
        emptyFieldList.Add(entry.Key.ToString())
        
      End If
      
    Next

    Return emptyFieldList
  
  End Function
  
  Sub EmployeeFormView_ModeChanging(ByVal sender As Object, ByVal e As FormViewModeEventArgs) Handles EmployeeFormView.ModeChanging
  
    If e.CancelingEdit Then
      
      ' The user canceled the update operation.
      ' Clear the error message label.
      MessageLabel.Text = ""
    
    End If
    
  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>FormView Example</h3>
                       
      <asp:formview id="EmployeeFormView"
        datasourceid="EmployeeSource"
        allowpaging="true"
        datakeynames="EmployeeID"
        headertext="Employee Record"
        emptydatatext="No employees found."
        runat="server">
        
        <headerstyle backcolor="CornFlowerBlue"
          forecolor="White"
          font-size="14"
          horizontalalign="Center"  
          wrap="false"/>
        <rowstyle backcolor="LightBlue"
          wrap="false"/>
        <pagerstyle backcolor="CornFlowerBlue"/>

        <itemtemplate>
          <table>
            <tr>
              <td rowspan="6">
                <asp:image id="EmployeeImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <%# Eval("FirstName") %> <%# Eval("LastName") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <%# Eval("Title") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Hire Date:</b>                 
              </td>
              <td>
                <%# Eval("HireDate","{0:d}") %>
              </td>
            </tr>
            <tr style="height:150; vertical-align:top">
              <td>
                <b>Address:</b>
              </td>
              <td>
                <%# Eval("Address") %><br/>
                <%# Eval("City") %> <%# Eval("Region") %>
                <%# Eval("PostalCode") %><br/>
                <%# Eval("Country") %>   
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="Edit"
                  text="Edit"
                  commandname="Edit"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </itemtemplate>
        <edititemtemplate>
          <table>
            <tr>
              <td rowspan="6">
                <asp:image id="EmployeeEditImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <asp:textbox id="FirstNameUpdateTextBox"
                  text='<%# Bind("FirstName") %>'
                  runat="server"/>
                <asp:textbox id="LastNameUpdateTextBox"
                  text='<%# Bind("LastName") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <asp:textbox id="TitleUpdateTextBox"
                  text='<%# Bind("Title") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td>
                <b>Hire Date:</b>                 
              </td>
              <td>
                <asp:textbox id="HireDateUpdateTextBox"
                  text='<%# Bind("HireDate", "{0:d}") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr style="height:150; vertical-align:top">
              <td>
                <b>Address:</b>
              </td>
              <td>
                <asp:textbox id="AddressUpdateTextBox"
                  text='<%# Bind("Address") %>'
                  runat="server"/>
                <br/>
                <asp:textbox id="CityUpdateTextBox"
                  text='<%# Bind("City") %>'
                  runat="server"/> 
                <asp:textbox id="RegionUpdateTextBox"
                  text='<%# Bind("Region") %>'
                  width="40"
                  runat="server"/>
                <asp:textbox id="PostalCodeUpdateTextBox"
                  text='<%# Bind("PostalCode") %>'
                  width="60"
                  runat="server"/>
                <br/>
                <asp:textbox id="CountryUpdateTextBox"
                  text='<%# Bind("Country") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="UpdateButton"
                  text="Update"
                  commandname="Update"
                  runat="server"/>
                <asp:linkbutton id="CancelButton"
                  text="Cancel"
                  commandname="Cancel"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </edititemtemplate>
          
        <pagersettings position="Bottom"
          mode="Numeric"/> 
                  
      </asp:formview>
      
      <br/><br/>
      
      <asp:label id="MessageLabel"
          forecolor="Red"
          runat="server"/>
          
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="EmployeeSource"
        selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [Address], [City], [Region], [PostalCode], [Country], [HireDate], [PhotoPath] From [Employees]"
        updatecommand="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName, [Title]=@Title, [Address]=@Address, [City]=@City, [Region]=@Region, [PostalCode]=@PostalCode, [Country]=@Country Where [EmployeeID]=@EmployeeID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

The following example demonstrates how to use a FormView control to insert new records.

Important

The control in this example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.


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

<!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 runat="server">
    <title>FormView InsertItemTemplate Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>FormView InsertItemTemplate Example</h3>
                       
      <asp:formview id="EmployeeFormView"
        datasourceid="EmployeeSource"
        allowpaging="true"
        datakeynames="EmployeeID"
        emptydatatext="No employees found."  
        runat="server">
        
        <rowstyle backcolor="LightGreen"
          wrap="false"/>
        <insertrowstyle backcolor="LightBlue"
          wrap="false"/>

        <itemtemplate>
          <table>
            <tr>
              <td rowspan="5">
                <asp:image id="CompanyLogoImage"
                  imageurl="~/Images/Logo.jpg"
                  alternatetext="Company logo"
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <%# Eval("FirstName") %> <%# Eval("LastName") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <%# Eval("Title") %>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="NewButton"
                  text="New"
                  commandname="New"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </itemtemplate>
        <insertitemtemplate>
          <table>
            <tr>
              <td rowspan="4">
                <asp:image id="CompanyLogoEditImage"
                  imageurl="~/Images/Logo.jpg"
                  alternatetext="Company logo"
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b><asp:Label runat="server" 
                  AssociatedControlID="FirstNameInsertTextBox" 
                  Text="Name" />:</b>
              </td>
              <td>
                <asp:textbox id="FirstNameInsertTextBox"
                  text='<%# Bind("FirstName") %>'
                  runat="server"/>
                <asp:textbox id="LastNameInsertTextBox"
                  text='<%# Bind("LastName") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr>
              <td>
                <b><asp:Label runat="server" 
                  AssociatedControlID="TitleInsertTextBox" 
                  Text="Title" />:</b>
              </td>
              <td>
                <asp:textbox id="TitleInsertTextBox"
                  text='<%# Bind("Title") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="InsertButton"
                  text="Insert"
                  commandname="Insert"
                  runat="server" />
                <asp:linkbutton id="CancelButton"
                  text="Cancel"
                  commandname="Cancel"
                  runat="server" /> 
              </td>
            </tr>
          </table>       
        </insertitemtemplate> 
                  
      </asp:formview>

      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="EmployeeSource"
        selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [PhotoPath] From [Employees]"
        insertcommand="Insert Into [Employees] ([LastName], [FirstName], [Title]) VALUES (@LastName, @FirstName, @Title)"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

<%@ Page language="VB" %>

<!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 runat="server">
    <title>FormView InsertItemTemplate Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>FormView InsertItemTemplate Example</h3>
                       
      <asp:formview id="EmployeeFormView"
        datasourceid="EmployeeSource"
        allowpaging="true"
        datakeynames="EmployeeID"
        emptydatatext="No employees found."  
        runat="server">
        
        <rowstyle backcolor="LightGreen"
          wrap="false"/>
        <insertrowstyle backcolor="LightBlue"
          wrap="false"/>

        <itemtemplate>
          <table>
            <tr>
              <td rowspan="5">
                <asp:image id="CompanyLogoImage"
                  imageurl="~/Images/Logo.jpg"
                  alternatetext="Company logo"
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <%# Eval("FirstName") %> <%# Eval("LastName") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <%# Eval("Title") %>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="NewButton"
                  text="New"
                  commandname="New"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </itemtemplate>
        <insertitemtemplate>
          <table>
            <tr>
              <td rowspan="4">
                <asp:image id="CompanyLogoEditImage"
                  imageurl="~/Images/Logo.jpg"
                  alternatetext="Company logo"
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b><asp:Label runat="server" 
                  AssociatedControlID="FirstNameInsertTextBox" 
                  Text="Name" />:</b>
              </td>
              <td>
                <asp:textbox id="FirstNameInsertTextBox"
                  text='<%# Bind("FirstName") %>'
                  runat="server"/>
                <asp:textbox id="LastNameInsertTextBox"
                  text='<%# Bind("LastName") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr>
              <td>
                <b><asp:Label runat="server" 
                  AssociatedControlID="TitleInsertTextBox" 
                  Text="Title" />:</b>
              </td>
              <td>
                <asp:textbox id="TitleInsertTextBox"
                  text='<%# Bind("Title") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="InsertButton"
                  text="Insert"
                  commandname="Insert"
                  runat="server" />
                <asp:linkbutton id="CancelButton"
                  text="Cancel"
                  commandname="Cancel"
                  runat="server" /> 
              </td>
            </tr>
          </table>       
        </insertitemtemplate> 
                  
      </asp:formview>

      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="EmployeeSource"
        selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [PhotoPath] From [Employees]"
        insertcommand="Insert Into [Employees] ([LastName], [FirstName], [Title]) VALUES (@LastName, @FirstName, @Title)"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

Remarks

In this topic:

Introduction

The FormView control is used to display a single record from a data source. It is similar to the DetailsView control, except it displays user-defined templates instead of row fields. Creating your own templates gives you greater flexibility in controlling how the data is displayed. The FormView control supports the following features:

  • Binding to data source controls, such as SqlDataSource and ObjectDataSource.

  • Built-in inserting capabilities.

  • Built-in updating and deleting capabilities.

  • Built-in paging capabilities.

  • Programmatic access to the FormView object model to dynamically set properties, handle events, and so on.

  • Customizable appearance through user-defined templates, themes, and styles.

Templates

For the FormView control to display content, you need to create templates for the different parts of the control. Most templates are optional; however, you must create a template for the mode in which the control is configured. For example, a FormView control that supports inserting records must have an insert item template defined. The following table lists the different templates that you can create.

Template type Description
EditItemTemplate Defines the content for the data row when the FormView control is in edit mode. This template usually contains input controls and command buttons with which the user can edit an existing record.
EmptyDataTemplate Defines the content for the empty data row displayed when the FormView control is bound to a data source that does not contain any records. This template usually contains content to alert the user that the data source does not contain any records.
FooterTemplate Defines the content for the footer row. This template usually contains any additional content you would like to display in the footer row. Note: As an alternative, you can simply specify text to display in the footer row by setting the FooterText property.
HeaderTemplate Defines the content for the header row. This template usually contains any additional content you would like to display in the header row. Note: As an alternative, you can simply specify text to display in the header row by setting the HeaderText property.
ItemTemplate Defines the content for the data row when the FormView control is in read-only mode. This template usually contains content to display the values of an existing record.
InsertItemTemplate Defines the content for the data row when the FormView control is in insert mode. This template usually contains input controls and command buttons with which the user can add a new record.
PagerTemplate Defines the content for the pager row displayed when the paging feature is enabled (when the AllowPaging property is set to true). This template usually contains controls with which the user can navigate to another record. Note: The FormView control has a built-in pager row user interface (UI). You need to create a pager template only if you want to create your own custom pager row.

To display the value of a field in an item template, use a data binding expression. For more information on data binding expressions, see Data-Binding Expression Syntax.

Input controls in the edit item template and insert item template can be bound to the fields of a data source by using a two-way binding expression. This allows the FormView control to automatically extract the values of the input control for an update or insert operation. Two-way binding expressions also allow input controls in an edit item template to automatically display the original field values. For more information on two-way binding expressions, see Binding to Databases.

Binding to Data

The FormView control can be bound to a data source control (such as SqlDataSource, ObjectDataSource, or AccessDataSource) or to any data source collection that implements the System.Collections.IEnumerable interface, such as System.Data.DataView, System.Collections.ArrayList, System.Collections.Generic.List<T>, or other collection types. Use one of the following methods to bind the FormView control to the appropriate data source type:

  • To bind to a data source control, set the DataSourceID property of the FormView control to the ID value of the data source control. The FormView control automatically binds to the specified data source control and can take advantage of the data source control's capabilities to perform inserting, updating, deleting, and paging functionality. This is the preferred method to bind to data.

  • To bind to a data source that implements the System.Collections.IEnumerable interface, programmatically set the DataSource property of the FormView control to the data source and then call the DataBind method. When using this method, the FormView control does not provide built-in inserting, updating, deleting, and paging functionality. You need to provide this functionality by using the appropriate event.

For more information on data binding, see ASP.NET Data Access Content Map.

Note

This control can be used to display user input, which might include malicious client script. Check any information that is sent from a client for executable script, SQL statements, or other code before displaying it in your application. Whenever possible, it is strongly recommended that values are HTML-encoded before they are displayed in this control. ASP.NET provides an input request validation feature to block script and HTML in user input. Validation server controls are also provided to assess user input. For more information, see Introduction to the Validation Controls.

Data Operations

The FormView control provides many built-in capabilities that allow the user to update, delete, insert, and page through items in the control. When the FormView control is bound to a data source control, the FormView control can take advantage of the data source control's capabilities and provide automatic updating, deleting, inserting, and paging functionality.

Note

The FormView control can provide support for update, delete, insert, and paging operations with other types of data sources; however, you must provide an appropriate event handler with the implementation for these operations.

Because the FormView control uses templates, it does not provide a way to automatically generate command buttons to perform updating, deleting, or inserting operations. You must manually include these command buttons in the appropriate template. The FormView control recognizes certain buttons that have their CommandName properties set to specific values. The following table lists the command buttons that the FormView control recognizes.

Button CommandName value Description
Cancel "Cancel" Used in updating or inserting operations to cancel the operation and to discard the values entered by the user. The FormView control then returns to the mode specified by the DefaultMode property.
Delete "Delete" Used in deleting operations to delete the displayed record from the data source. Raises the ItemDeleting and ItemDeleted events.
Edit "Edit" Used in updating operations to put the FormView control in edit mode. The content specified in the EditItemTemplate property is displayed for the data row.
Insert "Insert" Used in inserting operations to attempt to insert a new record in the data source using the values provided by the user. Raises the ItemInserting and ItemInserted events.
New "New" Used in inserting operations to put the FormView control in insert mode. The content specified in the InsertItemTemplate property is displayed for the data row.
Page "Page" Used in paging operations to represent a button in the pager row that performs paging. To specify the paging operation, set the CommandArgument property of the button to "Next", "Prev", "First", "Last", or the index of the page to which to navigate. Raises the PageIndexChanging and PageIndexChanged events. Note: This type of button is typically used only in the pager template.
Update "Update" Used in updating operations to attempt to update the displayed record in the data source with the values provided by the user. Raises the ItemUpdating and ItemUpdated events.

Unlike the Delete button (which deletes the displayed record immediately), when the Edit or New button is clicked, the FormView control goes into edit or insert mode, respectively. In edit mode, the content contained in the EditItemTemplate property is displayed for the current data item. Typically, the edit item template is defined such that the Edit button is replaced with an Update and a Cancel button. Input controls that are appropriate for the field's data type (such as a TextBox or a CheckBox control) are also usually displayed with a field's value for the user to modify. Clicking the Update button updates the record in the data source, while clicking the Cancel button abandons any changes.

Likewise, the content contained in the InsertItemTemplate property is displayed for the data item when the control is in insert mode. The insert item template is typically defined such that the New button is replaced with an Insert and a Cancel button, and empty input controls are displayed for the user to enter the values for the new record. Clicking the Insert button inserts the record in the data source, while clicking the Cancel button abandons any changes.

The FormView control provides a paging feature, which allows the user to navigate to other records in the data source. When enabled, a pager row is displayed in the FormView control that contains the page navigation controls. To enable paging, set the AllowPaging property to true. You can customize the pager row by setting the properties of objects contained in the PagerStyle and the PagerSettings property. Instead of using the built-in pager row UI, you can create your own UI by using the PagerTemplate property.

Customizing the User Interface

You can customize the appearance of the FormView control by setting the style properties for the different parts of the control. The following table lists the different style properties.

Style property Description
EditRowStyle The style settings for the data row when the FormView control is in edit mode.
EmptyDataRowStyle The style settings for the empty data row displayed in the FormView control when the data source does not contain any records.
FooterStyle The style settings for the footer row of the FormView control.
HeaderStyle The style settings for the header row of the FormView control.
InsertRowStyle The style settings for the data row when the FormView control is in insert mode.
PagerStyle The style settings for the pager row displayed in the FormView control when the paging feature is enabled.
RowStyle The style settings for the data row when the FormView control is in read-only mode.

Events

The FormView control provides several events that you can program against. This allows you to run a custom routine whenever an event occurs. The following table lists the events supported by the FormView control.

Event Description
ItemCommand Occurs when a button within a FormView control is clicked. This event is often used to perform a task when a button is clicked in the control.
ItemCreated Occurs after all FormViewRow objects are created in the FormView control. This event is often used to modify the values of a record before it is displayed.
ItemDeleted Occurs when a Delete button (a button with its CommandName property set to "Delete") is clicked, but after the FormView control deletes the record from the data source. This event is often used to check the results of the delete operation.
ItemDeleting Occurs when a Delete button is clicked, but before the FormView control deletes the record from the data source. This event is often used to cancel the delete operation.
ItemInserted Occurs when an Insert button (a button with its CommandName property set to "Insert") is clicked, but after the FormView control inserts the record. This event is often used to check the results of the insert operation.
ItemInserting Occurs when an Insert button is clicked, but before the FormView control inserts the record. This event is often used to cancel the insert operation.
ItemUpdated Occurs when an Update button (a button with its CommandName property set to "Update") is clicked, but after the FormView control updates the row. This event is often used to check the results of the update operation.
ItemUpdating Occurs when an Update button is clicked, but before the FormView control updates the record. This event is often used to cancel the update operation.
ModeChanged Occurs after the FormView control changes modes (to edit, insert, or read-only mode). This event is often used to perform a task when the FormView control changes modes.
ModeChanging Occurs before the FormView control changes modes (to edit, insert, or read-only mode). This event is often used to cancel a mode change.
PageIndexChanged Occurs when one of the pager buttons is clicked, but after the FormView control handles the paging operation. This event is commonly used when you need to perform a task after the user navigates to a different record in the control.
PageIndexChanging Occurs when one of the pager buttons is clicked, but before the FormView control handles the paging operation. This event is often used to cancel the paging operation.

Accessibility

For information about how to configure this control so that it generates markup that conforms to accessibility standards, see Accessibility in Visual Studio and ASP.NET and ASP.NET Controls and Accessibility.

Applying CSS Styles

The FormView control lets you specify CSS style rules in markup. If you use templates to customize the appearance of the FormView control, you can specify CSS styles in the markup in the templates. In that case, no extra outer table is required. You can prevent the table from being rendered by setting the RenderOuterTable property to false.

Declarative Syntax

<asp:FormView
    AccessKey="string"
    AllowPaging="True|False"
    BackColor="color name|#dddddd"
    BackImageUrl="uri"
    BorderColor="color name|#dddddd"
    BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
        Inset|Outset"
    BorderWidth="size"
    Caption="string"
    CaptionAlign="NotSet|Top|Bottom|Left|Right"
    CellPadding="integer"
    CellSpacing="integer"
    CssClass="string"
    DataKeyNames="string"
    DataMember="string"
    DataSource="string"
    DataSourceID="string"
    DefaultMode="ReadOnly|Edit|Insert"
    EmptyDataText="string"
    Enabled="True|False"
    EnableTheming="True|False"
    EnableViewState="True|False"
    Font-Bold="True|False"
    Font-Italic="True|False"
    Font-Names="string"
    Font-Overline="True|False"
    Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
        Large|X-Large|XX-Large"
    Font-Strikeout="True|False"
    Font-Underline="True|False"
    FooterText="string"
    ForeColor="color name|#dddddd"
    GridLines="None|Horizontal|Vertical|Both"
    HeaderText="string"
    Height="size"
    HorizontalAlign="NotSet|Left|Center|Right|Justify"
    ID="string"
    OnDataBinding="DataBinding event handler"
    OnDataBound="DataBound event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnItemCommand="ItemCommand event handler"
    OnItemCreated="ItemCreated event handler"
    OnItemDeleted="ItemDeleted event handler"
    OnItemDeleting="ItemDeleting event handler"
    OnItemInserted="ItemInserted event handler"
    OnItemInserting="ItemInserting event handler"
    OnItemUpdated="ItemUpdated event handler"
    OnItemUpdating="ItemUpdating event handler"
    OnLoad="Load event handler"
    OnModeChanged="ModeChanged event handler"
    OnModeChanging="ModeChanging event handler"
    OnPageIndexChanged="PageIndexChanged event handler"
    OnPageIndexChanging="PageIndexChanging event handler"
    OnPreRender="PreRender event handler"
    OnUnload="Unload event handler"
    PageIndex="integer"
    PagerSettings-FirstPageImageUrl="uri"
    PagerSettings-FirstPageText="string"
    PagerSettings-LastPageImageUrl="uri"
    PagerSettings-LastPageText="string"
    PagerSettings-Mode="NextPrevious|Numeric|NextPreviousFirstLast|
        NumericFirstLast"
    PagerSettings-NextPageImageUrl="uri"
    PagerSettings-NextPageText="string"
    PagerSettings-PageButtonCount="integer"
    PagerSettings-Position="Bottom|Top|TopAndBottom"
    PagerSettings-PreviousPageImageUrl="uri"
    PagerSettings-PreviousPageText="string"
    PagerSettings-Visible="True|False"
    RenderOuterTable="True|False"
    runat="server"
    SkinID="string"
    Style="string"
    TabIndex="integer"
    ToolTip="string"
    Visible="True|False"
    Width="size"
>
        <EditItemTemplate>
            <!-- child controls -->
        </EditItemTemplate>
        <EditRowStyle />
        <EmptyDataRowStyle />
        <EmptyDataTemplate>
            <!-- child controls -->
        </EmptyDataTemplate>
        <FooterStyle />
        <FooterTemplate>
            <!-- child controls -->
        </FooterTemplate>
        <HeaderStyle />
        <HeaderTemplate>
            <!-- child controls -->
        </HeaderTemplate>
        <InsertItemTemplate>
            <!-- child controls -->
        </InsertItemTemplate>
        <InsertRowStyle />
        <ItemTemplate>
            <!-- child controls -->
        </ItemTemplate>
        <PagerSettings
            FirstPageImageUrl="uri"
            FirstPageText="string"
            LastPageImageUrl="uri"
            LastPageText="string"
            Mode="NextPrevious|Numeric|NextPreviousFirstLast|
                NumericFirstLast"
            NextPageImageUrl="uri"
            NextPageText="string"
            OnPropertyChanged="PropertyChanged event handler"
            PageButtonCount="integer"
            Position="Bottom|Top|TopAndBottom"
            PreviousPageImageUrl="uri"
            PreviousPageText="string"
            Visible="True|False"
        />
        <PagerStyle />
        <PagerTemplate>
            <!-- child controls -->
        </PagerTemplate>
        <RowStyle />
</asp:FormView>

Constructors

FormView()

Initializes a new instance of the FormView class.

Properties

AccessKey

Gets or sets the access key that allows you to quickly navigate to the Web server control.

(Inherited from WebControl)
Adapter

Gets the browser-specific adapter for the control.

(Inherited from Control)
AllowPaging

Gets or sets a value indicating whether the paging feature is enabled.

AppRelativeTemplateSourceDirectory

Gets or sets the application-relative virtual directory of the Page or UserControl object that contains this control.

(Inherited from Control)
Attributes

Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.

(Inherited from WebControl)
BackColor

Gets or sets the background color of the Web server control.

(Inherited from WebControl)
BackImageUrl

Gets or sets the URL to an image to display in the background of a FormView control.

BindingContainer

Gets the control that contains this control's data binding.

(Inherited from Control)
BorderColor

Gets or sets the border color of the Web control.

(Inherited from WebControl)
BorderStyle

Gets or sets the border style of the Web server control.

(Inherited from WebControl)
BorderWidth

Gets or sets the border width of the Web server control.

(Inherited from WebControl)
BottomPagerRow

Gets the FormViewRow object that represents the pager row displayed at the bottom of the FormView control.

Caption

Gets or sets the text to render in an HTML caption element in a FormView control. This property is provided to make the control more accessible to users of assistive technology devices.

CaptionAlign

Gets or sets the horizontal or vertical position of the HTML caption element in a FormView control. This property is provided to make the control more accessible to users of assistive technology devices.

CellPadding

Gets or sets the amount of space between the contents of a cell and the cell's border.

CellSpacing

Gets or sets the amount of space between cells.

ChildControlsCreated

Gets a value that indicates whether the server control's child controls have been created.

(Inherited from Control)
ClientID

Gets the control ID for HTML markup that is generated by ASP.NET.

(Inherited from Control)
ClientIDMode

Gets or sets the algorithm that is used to generate the value of the ClientID property.

(Inherited from Control)
ClientIDSeparator

Gets a character value representing the separator character used in the ClientID property.

(Inherited from Control)
Context

Gets the HttpContext object associated with the server control for the current Web request.

(Inherited from Control)
Controls

Gets a collection of the child controls within the composite data-bound control.

(Inherited from CompositeDataBoundControl)
ControlStyle

Gets the style of the Web server control. This property is used primarily by control developers.

(Inherited from WebControl)
ControlStyleCreated

Gets a value indicating whether a Style object has been created for the ControlStyle property. This property is primarily used by control developers.

(Inherited from WebControl)
CssClass

Gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client.

(Inherited from WebControl)
CurrentMode

Gets the current data-entry mode of the FormView control.

DataItem

Gets the data item bound to the FormView control.

DataItemContainer

Gets a reference to the naming container if the naming container implements IDataItemContainer.

(Inherited from Control)
DataItemCount

Gets the number of data items in the data source.

DataItemIndex

Gets the index of the data item bound to the FormView control from the data source.

DataKey

Gets a DataKey object that represents the primary key of the displayed record.

DataKeyNames

Gets or sets an array that contains the names of the key fields for the data source.

DataKeysContainer

Gets a reference to the naming container if the naming container implements IDataKeysControl.

(Inherited from Control)
DataMember

Gets or sets the name of the list of data that the data-bound control binds to, in cases where the data source contains more than one distinct list of data items.

(Inherited from DataBoundControl)
DataSource

Gets or sets the object from which the data-bound control retrieves its list of data items.

(Inherited from BaseDataBoundControl)
DataSourceID

Gets or sets the ID of the control from which the data-bound control retrieves its list of data items.

(Inherited from DataBoundControl)
DataSourceObject

Gets an object that implements the IDataSource interface, which provides access to the object's data content.

(Inherited from DataBoundControl)
DefaultMode

Gets or sets the data-entry mode to which the FormView control returns after an update, insert, or cancel operation.

DeleteMethod

Gets or sets the name of the method on the page that is called when the control performs a delete operation.

DeleteMethod

Gets or sets the name of the method to call in order to delete data.

(Inherited from CompositeDataBoundControl)
DesignMode

Gets a value indicating whether a control is being used on a design surface.

(Inherited from Control)
EditItemTemplate

Gets or sets the custom content for an item in edit mode.

EditRowStyle

Gets a reference to the TableItemStyle object that allows you to set the appearance of the data row when a FormView control is in edit mode.

EmptyDataRowStyle

Gets a reference to the TableItemStyle object that allows you to set the appearance of the empty data row displayed when the data source bound to a FormView control does not contain any records.

EmptyDataTemplate

Gets or sets the user-defined content for the empty data row rendered when a FormView control is bound to a data source that does not contain any records.

EmptyDataText

Gets or sets the text to display in the empty data row rendered when a FormView control is bound to a data source that does not contain any records.

Enabled

Gets or sets a value indicating whether the Web server control is enabled.

(Inherited from WebControl)
EnableModelValidation

Gets or sets a value that indicates whether a validator control will handle exceptions that occur during insert or update operations.

EnableTheming

Gets or sets a value indicating whether themes apply to this control.

(Inherited from WebControl)
EnableViewState

Gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client.

(Inherited from Control)
Events

Gets a list of event handler delegates for the control. This property is read-only.

(Inherited from Control)
Font

Gets the font properties associated with the Web server control.

(Inherited from WebControl)
FooterRow

Gets the FormViewRow object that represents the footer row in a FormView control.

FooterStyle

Gets a reference to the TableItemStyle object that allows you to set the appearance of the footer row in a FormView control.

FooterTemplate

Gets or sets the user-defined content for the footer row in a FormView control.

FooterText

Gets or sets the text to display in the footer row of a FormView control.

ForeColor

Gets or sets the foreground color (typically the color of the text) of the Web server control.

(Inherited from WebControl)
GridLines

Gets or sets the gridline style for a FormView control.

HasAttributes

Gets a value indicating whether the control has attributes set.

(Inherited from WebControl)
HasChildViewState

Gets a value indicating whether the current server control's child controls have any saved view-state settings.

(Inherited from Control)
HeaderRow

Gets the FormViewRow object that represents the header row in a FormView control.

HeaderStyle

Gets a reference to the TableItemStyle object that allows you to set the appearance of the header row in a FormView control.

HeaderTemplate

Gets or sets the user-defined content for the header row in a FormView control.

HeaderText

Gets or sets the text to display in the header row of a FormView control.

Height

Gets or sets the height of the Web server control.

(Inherited from WebControl)
HorizontalAlign

Gets or sets the horizontal alignment of a FormView control on the page.

ID

Gets or sets the programmatic identifier assigned to the server control.

(Inherited from Control)
IdSeparator

Gets the character used to separate control identifiers.

(Inherited from Control)
Initialized

Gets a value indicating whether the data-bound control has been initialized.

(Inherited from BaseDataBoundControl)
InsertItemTemplate

Gets or sets the custom content for an item in insert mode.

InsertMethod

Gets or sets the name of the method on the page that is called when the control performs an insert operation.

InsertMethod

Gets or sets the name of the method to call in order to insert data.

(Inherited from CompositeDataBoundControl)
InsertRowStyle

Gets a reference to the TableItemStyle object that allows you to set the appearance of the data row in a FormView control when the control is in insert mode.

IsBoundUsingDataSourceID

Gets a value indicating whether the DataSourceID property is set.

(Inherited from BaseDataBoundControl)
IsChildControlStateCleared

Gets a value indicating whether controls contained within this control have control state.

(Inherited from Control)
IsDataBindingAutomatic

Gets a value that indicates whether data binding is automatic.

(Inherited from BaseDataBoundControl)
IsEnabled

Gets a value indicating whether the control is enabled.

(Inherited from WebControl)
IsTrackingViewState

Gets a value that indicates whether the server control is saving changes to its view state.

(Inherited from Control)
IsUsingModelBinders

Gets a value that indicates whether model binding is in use.

(Inherited from CompositeDataBoundControl)
IsViewStateEnabled

Gets a value indicating whether view state is enabled for this control.

(Inherited from Control)
ItemTemplate

Gets or sets the custom content for the data row in a FormView control when the control is in read-only mode.

ItemType

Gets or sets the name of the data item type for strongly typed data binding.

(Inherited from DataBoundControl)
LoadViewStateByID

Gets a value indicating whether the control participates in loading its view state by ID instead of index.

(Inherited from Control)
NamingContainer

Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same ID property value.

(Inherited from Control)
Page

Gets a reference to the Page instance that contains the server control.

(Inherited from Control)
PageCount

Gets the total number of pages required to display every record in the data source.

PageIndex

Gets or sets the index of the displayed page.

PagerSettings

Gets a reference to the PagerSettings object that allows you to set the properties of the pager buttons in a FormView control.

PagerStyle

Gets a reference to the TableItemStyle object that allows you to set the appearance of the pager row in a FormView control.

PagerTemplate

Gets or sets the custom content for the pager row in a FormView control.

Parent

Gets a reference to the server control's parent control in the page control hierarchy.

(Inherited from Control)
RenderingCompatibility

Gets a value that specifies the ASP.NET version that rendered HTML will be compatible with.

(Inherited from Control)
RenderOuterTable

Gets or sets a value that indicates whether the control encloses rendered HTML in a table element in order to apply inline styles.

RequiresDataBinding

Gets or sets a value indicating whether the DataBind() method should be called.

(Inherited from BaseDataBoundControl)
Row

Gets the FormViewRow object that represents the data row in a FormView control.

RowStyle

Gets a reference to the TableItemStyle object that allows you to set the appearance of the data row in a FormView control when the control is in read-only mode.

SelectArguments

Gets a DataSourceSelectArguments object that the data-bound control uses when retrieving data from a data source control.

(Inherited from DataBoundControl)
SelectedValue

Gets the data key value of the current record in a FormView control.

SelectMethod

The name of the method to call in order to read data.

(Inherited from DataBoundControl)
Site

Gets information about the container that hosts the current control when rendered on a design surface.

(Inherited from Control)
SkinID

Gets or sets the skin to apply to the control.

(Inherited from WebControl)
Style

Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.

(Inherited from WebControl)
SupportsDisabledAttribute

Gets a value that indicates whether the control should set the disabled attribute of the rendered HTML element to "disabled" when the control's IsEnabled property is false.

(Inherited from BaseDataBoundControl)
TabIndex

Gets or sets the tab index of the Web server control.

(Inherited from WebControl)
TagKey

Gets the HtmlTextWriterTag value for the FormView control.

TagName

Gets the name of the control tag. This property is used primarily by control developers.

(Inherited from WebControl)
TemplateControl

Gets or sets a reference to the template that contains this control.

(Inherited from Control)
TemplateSourceDirectory

Gets the virtual directory of the Page or UserControl that contains the current server control.

(Inherited from Control)
ToolTip

Gets or sets the text displayed when the mouse pointer hovers over the Web server control.

(Inherited from WebControl)
TopPagerRow

Gets the FormViewRow object that represents the pager row displayed at the top of a FormView control.

UniqueID

Gets the unique, hierarchically qualified identifier for the server control.

(Inherited from Control)
UpdateMethod

Gets or sets the name of the method on the page that is called when the control performs an update operation.

UpdateMethod

Gets or sets the name of the method to call in order to update data.

(Inherited from CompositeDataBoundControl)
ValidateRequestMode

Gets or sets a value that indicates whether the control checks client input from the browser for potentially dangerous values.

(Inherited from Control)
ViewState

Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.

(Inherited from Control)
ViewStateIgnoresCase

Gets a value that indicates whether the StateBag object is case-insensitive.

(Inherited from Control)
ViewStateMode

Gets or sets the view-state mode of this control.

(Inherited from Control)
Visible

Gets or sets a value that indicates whether a server control is rendered as UI on the page.

(Inherited from Control)
Width

Gets or sets the width of the Web server control.

(Inherited from WebControl)

Methods

AddAttributesToRender(HtmlTextWriter)

Adds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag. This method is used primarily by control developers.

(Inherited from WebControl)
AddedControl(Control, Int32)

Called after a child control is added to the Controls collection of the Control object.

(Inherited from Control)
AddParsedSubObject(Object)

Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's ControlCollection object.

(Inherited from Control)
ApplyStyle(Style)

Copies any nonblank elements of the specified style to the Web control, overwriting any existing style elements of the control. This method is primarily used by control developers.

(Inherited from WebControl)
ApplyStyleSheetSkin(Page)

Applies the style properties defined in the page style sheet to the control.

(Inherited from Control)
BeginRenderTracing(TextWriter, Object)

Begins design-time tracing of rendering data.

(Inherited from Control)
BuildProfileTree(String, Boolean)

Gathers information about the server control and delivers it to the Trace property to be displayed when tracing is enabled for the page.

(Inherited from Control)
ChangeMode(FormViewMode)

Switches the FormView control to the specified data-entry mode.

ClearCachedClientID()

Sets the cached ClientID value to null.

(Inherited from Control)
ClearChildControlState()

Deletes the control-state information for the server control's child controls.

(Inherited from Control)
ClearChildState()

Deletes the view-state and control-state information for all the server control's child controls.

(Inherited from Control)
ClearChildViewState()

Deletes the view-state information for all the server control's child controls.

(Inherited from Control)
ClearEffectiveClientIDMode()

Sets the ClientIDMode property of the current control instance and of any child controls to Inherit.

(Inherited from Control)
ConfirmInitState()

Sets the initialized state of the data-bound control.

(Inherited from BaseDataBoundControl)
CopyBaseAttributes(WebControl)

Copies the properties not encapsulated by the Style object from the specified Web server control to the Web server control that this method is called from. This method is used primarily by control developers.

(Inherited from WebControl)
CreateChildControls()

Creates the control hierarchy that is used to render a composite data-bound control based on the values that are stored in view state.

(Inherited from CompositeDataBoundControl)
CreateChildControls(IEnumerable, Boolean)

Creates the control hierarchy used to render the FormView control with the specified data source.

CreateControlCollection()

Creates a new ControlCollection object to hold the child controls (both literal and server) of the server control.

(Inherited from Control)
CreateControlStyle()

Creates a default table style object for the FormView control.

CreateDataSourceSelectArguments()

Creates the DataSourceSelectArguments object that contains the arguments that are passed to the data source for processing.

CreateRow(Int32, DataControlRowType, DataControlRowState)

Creates a FormViewRow object using the specified item index, row type, and row state.

CreateTable()

Creates the containing table for the FormView control.

DataBind()

Binds the data source to the FormView control.

DataBind(Boolean)

Binds a data source to the invoked server control and all its child controls with an option to raise the DataBinding event.

(Inherited from Control)
DataBindChildren()

Binds a data source to the server control's child controls.

(Inherited from Control)
DeleteItem()

Deletes the current record in the FormView control from the data source.

Dispose()

Enables a server control to perform final clean up before it is released from memory.

(Inherited from Control)
EndRenderTracing(TextWriter, Object)

Ends design-time tracing of rendering data.

(Inherited from Control)
EnsureChildControls()

Determines whether the server control contains child controls. If it does not, it creates child controls.

(Inherited from Control)
EnsureDataBound()

Makes certain that the FormView control is bound to data when appropriate.

EnsureID()

Creates an identifier for controls that do not have an identifier assigned.

(Inherited from Control)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
ExtractRowValues(IOrderedDictionary, Boolean)

Retrieves the values of each field declared within the data row and stores them in the specified IOrderedDictionary object.

FindControl(String)

Searches the current naming container for a server control with the specified id parameter.

(Inherited from Control)
FindControl(String, Int32)

Searches the current naming container for a server control with the specified id and an integer, specified in the pathOffset parameter, which aids in the search. You should not override this version of the FindControl method.

(Inherited from Control)
Focus()

Sets input focus to a control.

(Inherited from Control)
GetData()

Retrieves a DataSourceView object that the data-bound control uses to perform data operations.

(Inherited from DataBoundControl)
GetDataSource()

Retrieves the IDataSource interface that the data-bound control is associated with, if any.

(Inherited from DataBoundControl)
GetDesignModeState()

Gets design-time data for a control.

(Inherited from Control)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetRouteUrl(Object)

Gets the URL that corresponds to a set of route parameters.

(Inherited from Control)
GetRouteUrl(RouteValueDictionary)

Gets the URL that corresponds to a set of route parameters.

(Inherited from Control)
GetRouteUrl(String, Object)

Gets the URL that corresponds to a set of route parameters and a route name.

(Inherited from Control)
GetRouteUrl(String, RouteValueDictionary)

Gets the URL that corresponds to a set of route parameters and a route name.

(Inherited from Control)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetUniqueIDRelativeTo(Control)

Returns the prefixed portion of the UniqueID property of the specified control.

(Inherited from Control)
HasControls()

Determines if the server control contains any child controls.

(Inherited from Control)
HasEvents()

Returns a value indicating whether events are registered for the control or any child controls.

(Inherited from Control)
InitializePager(FormViewRow, PagedDataSource)

Creates the pager row for the FormView control.

InitializeRow(FormViewRow)

Initializes the specified FormViewRow object.

InsertItem(Boolean)

Inserts the current record in the data source.

IsBindableType(Type)

Determines whether the specified data type can be bound to a field in the FormView control.

IsLiteralContent()

Determines if the server control holds only literal content.

(Inherited from Control)
LoadControlState(Object)

Loads the state of the FormView control properties that need to be persisted, even when the EnableViewState property is set to false.

LoadViewState(Object)

Loads the previously saved view state of the FormView control.

MapPathSecure(String)

Retrieves the physical path that a virtual path, either absolute or relative, maps to.

(Inherited from Control)
MarkAsDataBound()

Sets the state of the control in view state as successfully bound to data.

(Inherited from DataBoundControl)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MergeStyle(Style)

Copies any nonblank elements of the specified style to the Web control, but will not overwrite any existing style elements of the control. This method is used primarily by control developers.

(Inherited from WebControl)
ModifiedOuterTableStylePropertyName()

Determines whether the table-specific CSS style rules that are associated with the FormView control are set to their default values.

OnBubbleEvent(Object, EventArgs)

Handles an event passed up through the control hierarchy.

OnCreatingModelDataSource(CreatingModelDataSourceEventArgs)

Raises the CreatingModelDataSource event.

(Inherited from DataBoundControl)
OnDataBinding(EventArgs)

Raises the DataBinding event.

(Inherited from Control)
OnDataBound(EventArgs)

Raises the DataBound event.

(Inherited from BaseDataBoundControl)
OnDataPropertyChanged()

Rebinds the data-bound control to its data after one of the base data source identification properties changes.

(Inherited from DataBoundControl)
OnDataSourceViewChanged(Object, EventArgs)

Raises the DataSourceViewChanged event.

(Inherited from DataBoundControl)
OnInit(EventArgs)

Raises the Init event.

OnItemCommand(FormViewCommandEventArgs)

Raises the ItemCommand event.

OnItemCreated(EventArgs)

Raises the ItemCreated event.

OnItemDeleted(FormViewDeletedEventArgs)

Raises the ItemDeleted event.

OnItemDeleting(FormViewDeleteEventArgs)

Raises the ItemDeleting event.

OnItemInserted(FormViewInsertedEventArgs)

Raises the ItemInserted event.

OnItemInserting(FormViewInsertEventArgs)

Raises the ItemInserting event.

OnItemUpdated(FormViewUpdatedEventArgs)

Raises the ItemUpdated event.

OnItemUpdating(FormViewUpdateEventArgs)

Raises the ItemUpdating event.

OnLoad(EventArgs)

Handles the Load event.

(Inherited from DataBoundControl)
OnModeChanged(EventArgs)

Raises the ModeChanged event.

OnModeChanging(FormViewModeEventArgs)

Raises the ModeChanging event.

OnPageIndexChanged(EventArgs)

Raises the PageIndexChanged event.

OnPageIndexChanging(FormViewPageEventArgs)

Raises the PageIndexChanging event.

OnPagePreLoad(Object, EventArgs)

Sets the initialized state of the data-bound control before the control is loaded.

(Inherited from DataBoundControl)
OnPreRender(EventArgs)

Handles the PreRender event.

(Inherited from BaseDataBoundControl)
OnUnload(EventArgs)

Raises the Unload event.

(Inherited from Control)
OpenFile(String)

Gets a Stream used to read a file.

(Inherited from Control)
PerformDataBinding(IEnumerable)

Binds the specified data source to the FormView control.

PerformSelect()

Retrieves data from the associated data source.

(Inherited from DataBoundControl)
PrepareControlHierarchy()

Sets up the control hierarchy of the FormView control.

RaiseBubbleEvent(Object, EventArgs)

Assigns any sources of the event and its information to the control's parent.

(Inherited from Control)
RaisePostBackEvent(String)

Raises the appropriate events for the FormView control when it posts back to the server.

RemovedControl(Control)

Called after a child control is removed from the Controls collection of the Control object.

(Inherited from Control)
Render(HtmlTextWriter)

Displays the FormView control on the client.

RenderBeginTag(HtmlTextWriter)

Renders the HTML opening tag of the control to the specified writer. This method is used primarily by control developers.

(Inherited from WebControl)
RenderChildren(HtmlTextWriter)

Outputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client.

(Inherited from Control)
RenderContents(HtmlTextWriter)

Renders the contents of the control to the specified writer. This method is used primarily by control developers.

(Inherited from WebControl)
RenderControl(HtmlTextWriter)

Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.

(Inherited from Control)
RenderControl(HtmlTextWriter, ControlAdapter)

Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object.

(Inherited from Control)
RenderEndTag(HtmlTextWriter)

Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers.

(Inherited from WebControl)
ResolveAdapter()

Gets the control adapter responsible for rendering the specified control.

(Inherited from Control)
ResolveClientUrl(String)

Gets a URL that can be used by the browser.

(Inherited from Control)
ResolveUrl(String)

Converts a URL into one that is usable on the requesting client.

(Inherited from Control)
SaveControlState()

Saves the state of the FormView control properties that need to be persisted, even when the EnableViewState property is set to false.

SaveViewState()

Saves the current view state of the FormView control.

SetDesignModeState(IDictionary)

Sets design-time data for a control.

(Inherited from Control)
SetPageIndex(Int32)

Sets the index of the currently displayed page in the FormView control.

SetRenderMethodDelegate(RenderMethod)

Assigns an event handler delegate to render the server control and its content into its parent control.

(Inherited from Control)
SetTraceData(Object, Object)

Sets trace data for design-time tracing of rendering data, using the trace data key and the trace data value.

(Inherited from Control)
SetTraceData(Object, Object, Object)

Sets trace data for design-time tracing of rendering data, using the traced object, the trace data key, and the trace data value.

(Inherited from Control)
ToString()

Returns a string that represents the current object.

(Inherited from Object)
TrackViewState()

Marks the starting point at which to begin tracking and saving view-state changes to the FormView control.

UpdateItem(Boolean)

Updates the current record in the data source.

ValidateDataSource(Object)

Verifies that the object a data-bound control binds to is one it can work with.

(Inherited from DataBoundControl)

Events

CallingDataMethods

Occurs when data methods are being called.

(Inherited from DataBoundControl)
CreatingModelDataSource

Occurs when the ModelDataSource object is being created.

(Inherited from DataBoundControl)
DataBinding

Occurs when the server control binds to a data source.

(Inherited from Control)
DataBound

Occurs after the server control binds to a data source.

(Inherited from BaseDataBoundControl)
Disposed

Occurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested.

(Inherited from Control)
Init

Occurs when the server control is initialized, which is the first step in its lifecycle.

(Inherited from Control)
ItemCommand

Occurs when a button within a FormView control is clicked.

ItemCreated

Occurs after all the rows are created in a FormView control.

ItemDeleted

Occurs when a Delete button within a FormView control is clicked, but after the delete operation.

ItemDeleting

Occurs when a Delete button within a FormView control is clicked, but before the delete operation.

ItemInserted

Occurs when an Insert button within a FormView control is clicked, but after the insert operation.

ItemInserting

Occurs when an Insert button within a FormView control is clicked, but before the insert operation.

ItemUpdated

Occurs when an Update button within a FormView control is clicked, but after the update operation.

ItemUpdating

Occurs when an Update button within a FormView control is clicked, but before the update operation.

Load

Occurs when the server control is loaded into the Page object.

(Inherited from Control)
ModeChanged

Occurs when the FormView control switches between edit, insert, and read-only mode, but after the mode has changed.

ModeChanging

Occurs when the FormView control switches between edit, insert, and read-only mode, but before the mode changes.

PageIndexChanged

Occurs when the value of the PageIndex property changes after a paging operation.

PageIndexChanging

Occurs when the value of the PageIndex property changes before a paging operation.

PreRender

Occurs after the Control object is loaded but prior to rendering.

(Inherited from Control)
Unload

Occurs when the server control is unloaded from memory.

(Inherited from Control)

Explicit Interface Implementations

IAttributeAccessor.GetAttribute(String)

Gets an attribute of the Web control with the specified name.

(Inherited from WebControl)
IAttributeAccessor.SetAttribute(String, String)

Sets an attribute of the Web control to the specified name and value.

(Inherited from WebControl)
IControlBuilderAccessor.ControlBuilder

For a description of this member, see ControlBuilder.

(Inherited from Control)
IControlDesignerAccessor.GetDesignModeState()

For a description of this member, see GetDesignModeState().

(Inherited from Control)
IControlDesignerAccessor.SetDesignModeState(IDictionary)

For a description of this member, see SetDesignModeState(IDictionary).

(Inherited from Control)
IControlDesignerAccessor.SetOwnerControl(Control)

For a description of this member, see SetOwnerControl(Control).

(Inherited from Control)
IControlDesignerAccessor.UserData

For a description of this member, see UserData.

(Inherited from Control)
IDataBindingsAccessor.DataBindings

For a description of this member, see DataBindings.

(Inherited from Control)
IDataBindingsAccessor.HasDataBindings

For a description of this member, see HasDataBindings.

(Inherited from Control)
IDataBoundControl.DataKeyNames

Gets or sets an array that contains the names of the primary-key fields of the items that are displayed in the FormView control.

IDataBoundControl.DataMember

Gets or sets the name of the list of data items that the FormView control binds to when the data source contains more than one list of data items.

IDataBoundControl.DataSource

Gets or sets the object that contains the list of data that the FormView control retrieves.

IDataBoundControl.DataSourceID

Gets or sets the ID of the data source control that contains the list of data items that the FormView control retrieves.

IDataBoundControl.DataSourceObject

Gets the data source object that contains the list of data items that the FormView control retrieves.

IDataBoundItemControl.DataKey

Gets the object that represents the data-key value of the row in the FormView control.

IDataBoundItemControl.Mode

Gets the current mode of the FormView control.

IDataItemContainer.DataItemIndex

For a description of this member, see DataItemIndex.

IDataItemContainer.DisplayIndex

For a description of this member, see DisplayIndex.

IExpressionsAccessor.Expressions

For a description of this member, see Expressions.

(Inherited from Control)
IExpressionsAccessor.HasExpressions

For a description of this member, see HasExpressions.

(Inherited from Control)
IParserAccessor.AddParsedSubObject(Object)

For a description of this member, see AddParsedSubObject(Object).

(Inherited from Control)
IPostBackContainer.GetPostBackOptions(IButtonControl)

Determines the postback event options for the FormView control.

IPostBackEventHandler.RaisePostBackEvent(String)

Raises events for the FormView control when it posts back to the server.

Extension Methods

EnablePersistedSelection(BaseDataBoundControl)
Obsolete.

Enables selection to be persisted in data controls that support selection and paging.

FindDataSourceControl(Control)

Returns the data source that is associated with the data control for the specified control.

FindFieldTemplate(Control, String)

Returns the field template for the specified column in the specified control's naming container.

FindMetaTable(Control)

Returns the metatable object for the containing data control.

GetDefaultValues(INamingContainer)

Gets the collection of the default values for the specified data control.

GetMetaTable(INamingContainer)

Gets the table metadata for the specified data control.

SetMetaTable(INamingContainer, MetaTable)

Sets the table metadata for the specified data control.

SetMetaTable(INamingContainer, MetaTable, IDictionary<String,Object>)

Sets the table metadata and default value mapping for the specified data control.

SetMetaTable(INamingContainer, MetaTable, Object)

Sets the table metadata and default value mapping for the specified data control.

TryGetMetaTable(INamingContainer, MetaTable)

Determines whether table metadata is available.

EnableDynamicData(INamingContainer, Type)

Enables Dynamic Data behavior for the specified data control.

EnableDynamicData(INamingContainer, Type, IDictionary<String,Object>)

Enables Dynamic Data behavior for the specified data control.

EnableDynamicData(INamingContainer, Type, Object)

Enables Dynamic Data behavior for the specified data control.

Applies to

See also