다음을 통해 공유


TemplateField 생성자

정의

TemplateField 클래스의 새 인스턴스를 초기화합니다.

public:
 TemplateField();
public TemplateField ();
Public Sub New ()

예제

다음 코드 예제에는 동적으로 추가 하는 생성자를 사용 하는 방법을 보여 줍니다.는 TemplateField 필드 열을 GridView 컨트롤입니다.


<%@ 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">
  
  // Create a template class to represent a dynamic template column.
  public class GridViewTemplate : ITemplate
  {
    private DataControlRowType templateType;
    private string columnName;
   
    public GridViewTemplate(DataControlRowType type, string colname)
    {
      templateType = type;
      columnName = colname;
    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
      // Create the content for the different row types.
      switch(templateType)
      {
        case DataControlRowType.Header:
          // Create the controls to put in the header
          // section and set their properties.
          Literal lc = new Literal();
          lc.Text = "<b>" + columnName + "</b>";
          
          // Add the controls to the Controls collection
          // of the container.
          container.Controls.Add(lc);
          break;
        case DataControlRowType.DataRow:
          // Create the controls to put in a data row
          // section and set their properties.
          Label firstName = new Label();
          Label lastName = new Label();
          
          Literal spacer = new Literal();
          spacer.Text = " ";
          
          // To support data binding, register the event-handling methods
          // to perform the data binding. Each control needs its own event
          // handler.
          firstName.DataBinding += new EventHandler(this.FirstName_DataBinding);
          lastName.DataBinding += new EventHandler(this.LastName_DataBinding);
          
          // Add the controls to the Controls collection
          // of the container.
          container.Controls.Add(firstName);
          container.Controls.Add (spacer);
          container.Controls.Add(lastName);
          break;
          
        // Insert cases to create the content for the other 
        // row types, if desired.
          
        default:
          // Insert code to handle unexpected values.
          break; 
      }
    }
    
    private void FirstName_DataBinding(Object sender, EventArgs e)
    {
      // Get the Label control to bind the value. The Label control
      // is contained in the object that raised the DataBinding 
      // event (the sender parameter).
      Label l = (Label)sender;
      
      // Get the GridViewRow object that contains the Label control. 
      GridViewRow row = (GridViewRow)l.NamingContainer;
      
      // Get the field value from the GridViewRow object and 
      // assign it to the Text property of the Label control.
      l.Text = DataBinder.Eval(row.DataItem, "au_fname").ToString();
    }
    
    private void LastName_DataBinding(Object sender, EventArgs e)
    { 
      // Get the Label control to bind the value. The Label control
      // is contained in the object that raised the DataBinding 
      // event (the sender parameter).
      Label l = (Label)sender;
      
      // Get the GridViewRow object that contains the Label control.
      GridViewRow row = (GridViewRow)l.NamingContainer;
      
      // Get the field value from the GridViewRow object and 
      // assign it to the Text property of the Label control.
      l.Text = DataBinder.Eval(row.DataItem, "au_lname").ToString();
    }
  }

  void Page_Load(Object sender, EventArgs e)
  {
    
    // The field columns need to be created only when the page is
    // first loaded. 
    if (!IsPostBack)
    {
      // Dynamically create field columns to display the desired
      // fields from the data source. Create a TemplateField object 
      // to display an author's first and last name.
      TemplateField customField = new TemplateField();

      // Create the dynamic templates and assign them to 
      // the appropriate template property.
      customField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "Author Name");
      customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "Author Name");

      // Add the field column to the Columns collection of the
      // GridView control.
      AuthorsGridView.Columns.Add(customField);
    }
  
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>TemplateField Constructor Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>TemplateField Constructor Example</h3>

      <asp:gridview id="AuthorsGridView" 
        datasourceid="AuthorsSqlDataSource" 
        autogeneratecolumns="False"
        runat="server">                
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects -->
      <!-- to the Pubs sample database.                        -->
      <asp:sqldatasource id="AuthorsSqlDataSource"  
        selectcommand="SELECT [au_fname], [au_lname] FROM [authors]"
        connectionstring="server=localhost;database=pubs;integrated security=SSPI"
        runat="server">
      </asp:sqldatasource>
            
    </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">
  
  ' Create a template class to represent a dynamic template column.
  Public Class GridViewTemplate   
    Implements ITemplate

    Private templateType As DataControlRowType
    Private columnName As String
   
    Sub New(ByVal type As DataControlRowType, ByVal colname As String)

      templateType = type
      columnName = colname
    
    End Sub

    Sub InstantiateIn(ByVal container As System.Web.UI.Control) _
      Implements ITemplate.InstantiateIn
      
      ' Create the content for the different row types.
      Select Case templateType

        Case DataControlRowType.Header
          ' Create the controls to put in the header
          ' section and set their properties.
          Dim lc As New Literal
          lc.Text = "<b>" & columnName & "</b>"
          
          ' Add the controls to the Controls collection
          ' of the container.
          container.Controls.Add(lc)

        Case DataControlRowType.DataRow
          ' Create the controls to put in a data row
          ' section and set their properties.
          Dim firstName As New Label
          Dim lastName As New Label
          
          Dim spacer = New Literal
          spacer.Text = " "
          
          ' To support data binding, register the event-handling methods
          ' to perform the data binding. Each control needs its own event
          ' handler.
          AddHandler firstName.DataBinding, AddressOf FirstName_DataBinding
          AddHandler lastName.DataBinding, AddressOf LastName_DataBinding
          
          ' Add the controls to the Controls collection
          ' of the container.
          container.Controls.Add(firstName)
          container.Controls.Add(spacer)
          container.Controls.Add(lastName)
          
          ' Insert cases to create the content for the other 
          ' row types, if desired.
          
        Case Else
        
          ' Insert code to handle unexpected values. 
          
      End Select
      
    End Sub
    
    Private Sub FirstName_DataBinding(ByVal sender As Object, ByVal e As EventArgs)

      ' Get the Label control to bind the value. The Label control
      ' is contained in the object that raised the DataBinding 
      ' event (the sender parameter).
      Dim l As Label = CType(sender, Label)
      
      ' Get the GridViewRow object that contains the Label control. 
      Dim row As GridViewRow = CType(l.NamingContainer, GridViewRow)
      
      ' Get the field value from the GridViewRow object and 
      ' assign it to the Text property of the Label control.
      l.Text = DataBinder.Eval(row.DataItem, "au_fname").ToString()
    
    End Sub
    
    Private Sub LastName_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
 
      ' Get the Label control to bind the value. The Label control
      ' is contained in the object that raised the DataBinding 
      ' event (the sender parameter).
      Dim l As Label = CType(sender, Label)
      
      ' Get the GridViewRow object that contains the Label control.
      Dim row As GridViewRow = CType(l.NamingContainer, GridViewRow)
      
      ' Get the field value from the GridViewRow object and 
      ' assign it to the Text property of the Label control.
      l.Text = DataBinder.Eval(row.DataItem, "au_lname").ToString()
    
    End Sub
    
  End Class

  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    
    ' The field columns need to be created only when the page is
    ' first loaded. 
    If Not IsPostBack Then
      ' Dynamically create field columns to display the desired
      ' fields from the data source. Create a TemplateField object 
      ' to display an author's first and last name.
      Dim customField As New TemplateField

      ' Create the dynamic templates and assign them to
      ' the appropriate template property.
      customField.ItemTemplate = New GridViewTemplate(DataControlRowType.DataRow, "Author Name")
      customField.HeaderTemplate = New GridViewTemplate(DataControlRowType.Header, "Author Name")

      ' Add the field column to the Columns collection of the
      ' GridView control.
      AuthorsGridView.Columns.Add(customField)
    End If
  
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>TemplateField Constructor Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>TemplateField Constructor Example</h3>

      <asp:gridview id="AuthorsGridView" 
        datasourceid="AuthorsSqlDataSource" 
        autogeneratecolumns="False"
        runat="server">                
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects -->
      <!-- to the Pubs sample database.                        -->
      <asp:sqldatasource id="AuthorsSqlDataSource"  
        selectcommand="SELECT [au_fname], [au_lname] FROM [authors]"
        connectionstring="server=localhost;database=pubs;integrated security=SSPI"
        runat="server">
      </asp:sqldatasource>
            
    </form>
  </body>
</html>

설명

이 생성자의 새 인스턴스를 초기화 하는 데는 TemplateField 클래스입니다. 이 생성자는 필드를 동적으로 생성된 하는 데이터 바인딩된 컨트롤을 추가할 때 일반적으로 사용 됩니다.

동적으로 추가 하는 TemplateField 데이터 바인딩된 컨트롤에 개체를 새 TemplateField 개체 적절 한 템플릿을 정의 하 고 다음 데이터 바인딩된 컨트롤의 필드 컬렉션에 추가 합니다. 예를 들어, 사용 중인 경우는 GridView 컨트롤을 추가 합니다 TemplateField 개체를 Columns 컬렉션.

참고

데이터 바인딩된 컨트롤에 필드를 동적으로 추가할 수 있습니다, 있지만 것이 좋습니다는 필드 정적으로 선언 하 고 다음 표시 하거나 숨길 수를 적절 하 게 합니다. 모든 필드를 정적으로 선언 된 부모 데이터 바인딩된 컨트롤에 대 한 뷰 상태의 크기를 줄입니다.

적용 대상

추가 정보