TemplateField.AlternatingItemTemplate Свойство
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает или задает шаблон для отображения переменных элементов в объекте TemplateField .
public:
virtual property System::Web::UI::ITemplate ^ AlternatingItemTemplate { System::Web::UI::ITemplate ^ get(); void set(System::Web::UI::ITemplate ^ value); };
[System.ComponentModel.Browsable(false)]
[System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)]
[System.Web.UI.TemplateContainer(typeof(System.Web.UI.IDataItemContainer), System.ComponentModel.BindingDirection.TwoWay)]
public virtual System.Web.UI.ITemplate AlternatingItemTemplate { get; set; }
[<System.ComponentModel.Browsable(false)>]
[<System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)>]
[<System.Web.UI.TemplateContainer(typeof(System.Web.UI.IDataItemContainer), System.ComponentModel.BindingDirection.TwoWay)>]
member this.AlternatingItemTemplate : System.Web.UI.ITemplate with get, set
Public Overridable Property AlternatingItemTemplate As ITemplate
Значение свойства
Реализованный ITemplateобъект, содержащий шаблон для отображения переменных элементов в объекте TemplateField. Значение по умолчанию null— это означает, что это свойство не задано.
- Атрибуты
Примеры
В следующем примере кода показано, как использовать AlternatingItemTemplate свойство для создания пользовательского GridView шаблона для чередующихся элементов в TemplateField столбце поля элемента управления. Шаблон представляет собой вариант шаблона, указанного ItemTemplate свойством, где изображение отображается на противоположной стороне ячейки.
<%@ 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>TemplateField AlternatingItemTemplate Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>TemplateField AlternatingItemTemplate Example</h3>
<!-- Populate the Columns collection declaratively. -->
<!-- Create a TemplateField field column that has both -->
<!-- an item template and an alternating item template. -->
<!-- The item template displays an author's image on the -->
<!-- left side of the column, while the alternating item -->
<!-- template displays an author's image on the right side. -->
<!-- For this example, the zip field is used for the -->
<!-- values of the image URL. For your application, you -->
<!-- should use a field that contains valid URLs to -->
<!-- images. -->
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="False"
runat="server">
<columns>
<asp:templatefield headertext="Author">
<itemtemplate>
<asp:image id="LeftAuthorImage"
imageurl='<%# Eval("zip") %>'
alternatetext="Author Photo"
runat="server"/>
<asp:label id="LeftFirstNameLabel"
text= '<%# Eval("au_fname") %>'
runat="server"/>
<asp:label id="LeftLastNameLabel"
text= '<%# Eval("au_lname") %>'
runat="server"/>
</itemtemplate>
<alternatingitemtemplate>
<asp:label id="RightFirstNameLabel"
text= '<%# Eval("au_fname") %>'
runat="server"/>
<asp:label id="RightLastNameLabel"
text= '<%# Eval("au_lname") %>'
runat="server"/>
<asp:image id="RightAuthorImage"
imageurl='<%# Eval("zip") %>'
alternatetext="Author Photo"
runat="server"/>
</alternatingitemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_lname], [au_fname], [zip] 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">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>TemplateField AlternatingItemTemplate Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>TemplateField AlternatingItemTemplate Example</h3>
<!-- Populate the Columns collection declaratively. -->
<!-- Create a TemplateField field column that has both -->
<!-- an item template and an alternating item template. -->
<!-- The item template displays an author's image on the -->
<!-- left side of the column, while the alternating item -->
<!-- template displays an author's image on the right side. -->
<!-- For this example, the zip field is used for the -->
<!-- values of the image URL. For your application, you -->
<!-- should use a field that contains valid URLs to -->
<!-- images. -->
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="False"
runat="server">
<columns>
<asp:templatefield headertext="Author">
<itemtemplate>
<asp:image id="LeftAuthorImage"
imageurl='<%# Eval("zip") %>'
alternatetext="Author Photo"
runat="server"/>
<asp:label id="LeftFirstNameLabel"
text= '<%# Eval("au_fname") %>'
runat="server"/>
<asp:label id="LeftLastNameLabel"
text= '<%# Eval("au_lname") %>'
runat="server"/>
</itemtemplate>
<alternatingitemtemplate>
<asp:label id="RightFirstNameLabel"
text= '<%# Eval("au_fname") %>'
runat="server"/>
<asp:label id="RightLastNameLabel"
text= '<%# Eval("au_lname") %>'
runat="server"/>
<asp:image id="RightAuthorImage"
imageurl='<%# Eval("zip") %>'
alternatetext="Author Photo"
runat="server"/>
</alternatingitemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_lname], [au_fname], [zip] FROM [authors]"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
Комментарии
AlternatingItemTemplate Используйте свойство, чтобы указать пользовательское содержимое, отображаемое для чередующихся элементов в объектеTemplateField. Определите содержимое, создав шаблон, указывающий способ отрисовки переменных элементов.
Замечание
Свойство AlternatingItemTemplate обычно используется в сочетании со ItemTemplate свойством для создания другого внешнего вида для каждого другого элемента в элементе управления с привязкой к данным.
Чтобы указать шаблон, сначала следует поместить теги открытия и закрытия между открывающим и закрывающим <AlternatingItemTemplate> тегами <TemplateField> элемента. Затем добавьте пользовательское содержимое между открывающим и закрывающим <AlternatingItemTemplate> тегами. Содержимое может быть таким же простым, как обычный текст или более сложным (например, внедрение других элементов управления в шаблон).
Чтобы программным способом получить доступ к элементу управления, определенному в шаблоне, сначала определите, какой TableCell объект в элементе управления с привязкой к данным содержит элемент управления. Затем используйте Controls коллекцию TableCell объекта для доступа к элементу управления. Можно также использовать FindControl метод TableCell объекта для поиска элемента управления, если элемент управления имеет указанное ID свойство.