.NET Framework Class Library ListView Class Displays the values of a data source by using user-defined templates. The ListView control enables users to select, sort, delete, edit, and insert records.

Inheritance Hierarchy
Namespace:
System.Web.UI.WebControls
Assembly:
System.Web.Extensions (in System.Web.Extensions.dll)

Syntax
<ControlValuePropertyAttribute("SelectedValue")> _
<ToolboxBitmapAttribute(GetType(ListView), "ListView.bmp")> _
Public Class ListView _
Inherits DataBoundControl _
Implements INamingContainer, IPageableItemContainer, IPersistedSelector, IDataKeysControl, _
IDataBoundListControl, IDataBoundControl
[ControlValuePropertyAttribute("SelectedValue")]
[ToolboxBitmapAttribute(typeof(ListView), "ListView.bmp")]
public class ListView : DataBoundControl, INamingContainer,
IPageableItemContainer, IPersistedSelector, IDataKeysControl, IDataBoundListControl, IDataBoundControl
[ControlValuePropertyAttribute(L"SelectedValue")]
[ToolboxBitmapAttribute(typeof(ListView), L"ListView.bmp")]
public ref class ListView : public DataBoundControl,
INamingContainer, IPageableItemContainer, IPersistedSelector, IDataKeysControl, IDataBoundListControl,
IDataBoundControl
[<ControlValuePropertyAttribute("SelectedValue")>]
[<ToolboxBitmapAttribute(typeof(ListView), "ListView.bmp")>]
type ListView =
class
inherit DataBoundControl
interface INamingContainer
interface IPageableItemContainer
interface IPersistedSelector
interface IDataKeysControl
interface IDataBoundListControl
interface IDataBoundControl
end
The ListView type exposes the following members.

Constructors
|
| Name | Description |
|---|
.gif) | ListView | Initializes a new instance of the ListView class. | Top

Properties

Methods
|
| Name | Description |
|---|
.gif) | AddAttributesToRender | 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.) | .gif) | AddControlToContainer | Adds the specified control to the specified container. | .gif) | AddedControl | Called after a child control is added to the Controls collection of the Control object. (Inherited from Control.) | .gif) | AddParsedSubObject | 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.) | .gif) | ApplyStyle | 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.) | .gif) | ApplyStyleSheetSkin | Applies the style properties defined in the page style sheet to the control. (Inherited from Control.) | .gif) | BuildProfileTree | Infrastructure. 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.) | .gif) | ClearCachedClientID | Infrastructure. Sets the cached ClientID value to nullNothingnullptra null reference (Nothing in Visual Basic). (Inherited from Control.) | .gif) | ClearChildControlState | Deletes the control-state information for the server control's child controls. (Inherited from Control.) | .gif) | ClearChildState | Deletes the view-state and control-state information for all the server control's child controls. (Inherited from Control.) | .gif) | ClearChildViewState | Deletes the view-state information for all the server control's child controls. (Inherited from Control.) | .gif) | ClearEffectiveClientIDMode | Infrastructure. Sets the ClientIDMode property of the current control instance and of any child controls to Inherit. (Inherited from Control.) | .gif) | ConfirmInitState | Sets the initialized state of the data-bound control. (Inherited from BaseDataBoundControl.) | .gif) | CopyBaseAttributes | 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.) | .gif) | CreateChildControls()()() | Creates the control hierarchy that is used to render the ListView control, based on the values that are stored in view state. (Overrides Control..::.CreateChildControls()()().) | .gif) | CreateChildControls(IEnumerable, Boolean) | Creates the control hierarchy that is used to render the ListView control by using the specified data source. | .gif) | CreateControlCollection | Creates a new ControlCollection object to hold the child controls (both literal and server) of the server control. (Inherited from Control.) | .gif) | CreateControlStyle | Creates the default style for the control. (Overrides WebControl..::.CreateControlStyle()()().) | .gif) | CreateDataItem | Creates a data item in the ListView control. | .gif) | CreateDataSourceSelectArguments | Creates the DataSourceSelectArguments object that contains the arguments that are passed to the data source. (Overrides DataBoundControl..::.CreateDataSourceSelectArguments()()().) | .gif) | CreateEmptyDataItem | Creates the EmptyDataTemplate template in the ListView control. | .gif) | CreateEmptyItem | Creates an empty item in the ListView control. | .gif) | CreateInsertItem | Creates an insert item in the ListView control. | .gif) | CreateItem | Creates a ListViewItem object with the specified type. | .gif) | CreateItemsInGroups | Creates the ListView control hierarchy in groups. | .gif) | CreateItemsWithoutGroups | Creates the ListView control hierarchy without groups. | .gif) | CreateLayoutTemplate | Creates the root container in the ListView control. | .gif) | CreateSuffixArrayList | Infrastructure. Creates an array of suffixes for ASP.NET to use when it generates the ClientID value. | .gif) | DataBind()()() | Binds a data source to the invoked server control and all its child controls. (Inherited from BaseDataBoundControl.) | .gif) | 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.) | .gif) | DataBindChildren | Binds a data source to the server control's child controls. (Inherited from Control.) | .gif) | DeleteItem | Deletes the record at the specified index from the data source. | .gif) | Dispose | Enables a server control to perform final clean up before it is released from memory. (Inherited from Control.) | .gif) | EnsureChildControls | Determines whether the server control contains child controls. If it does not, it creates child controls. (Inherited from Control.) | .gif) | EnsureDataBound | Calls the DataBind method if the DataSourceID property is set and the data-bound control is marked to require binding. (Inherited from BaseDataBoundControl.) | .gif) | EnsureID | Creates an identifier for controls that do not have an identifier assigned. (Inherited from Control.) | .gif) | EnsureLayoutTemplate | Ensures that the LayoutTemplate content is correctly created in the ListView control. | .gif) | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | .gif) | ExtractItemValues | Retrieves the values of each field that is declared in the specified item, and stores them in the specified IOrderedDictionary object. | .gif) | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | .gif) | FindControl(String) | Searches the current naming container for a server control with the specified id parameter. (Inherited from Control.) | .gif) | FindControl(String, Int32) | Infrastructure. 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.) | .gif) | FindPlaceholder | Searches the specified container for a control that has the specified identifier. | .gif) | Focus | Sets input focus to a control. (Inherited from Control.) | .gif) | GetData | Retrieves a DataSourceView object that the data-bound control uses to perform data operations. (Inherited from DataBoundControl.) | .gif) | GetDataSource | Retrieves the IDataSource interface that the data-bound control is associated with, if any. (Inherited from DataBoundControl.) | .gif) | GetDesignModeState | Infrastructure. Gets design-time data for a control. (Inherited from Control.) | .gif) | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | .gif) | GetRouteUrl(Object) | Gets the URL that corresponds to a set of route parameters. (Inherited from Control.) | .gif) | GetRouteUrl(RouteValueDictionary) | Gets the URL that corresponds to a set of route parameters. (Inherited from Control.) | .gif) | GetRouteUrl(String, Object) | Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.) | .gif) | GetRouteUrl(String, RouteValueDictionary) | Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.) | .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) | GetUniqueIDRelativeTo | Returns the prefixed portion of the UniqueID property of the specified control. (Inherited from Control.) | .gif) | HasControls | Determines if the server control contains any child controls. (Inherited from Control.) | .gif) | HasEvents | Returns a value indicating whether events are registered for the control or any child controls. (Inherited from Control.) | .gif) | InsertNewItem | Inserts the current record in the data source. | .gif) | InstantiateEmptyDataTemplate | Populates the specified Control object by using the child controls that are contained in the EmptyDataTemplate template. | .gif) | InstantiateEmptyItemTemplate | Populates the specified Control object by using the child controls that are contained in the EmptyItemTemplate template. | .gif) | InstantiateGroupSeparatorTemplate | Populates the specified Control object by using the child controls that are contained in the GroupSeparatorTemplate template. | .gif) | InstantiateGroupTemplate | Populates the specified Control object by using the child controls that are contained in the GroupTemplate template. | .gif) | InstantiateInsertItemTemplate | Populates the specified Control object by using the child controls that are contained in the InsertItemTemplate template. | .gif) | InstantiateItemSeparatorTemplate | Populates the specified Control object by using the child controls that are contained in the ItemSeparatorTemplate template. | .gif) | InstantiateItemTemplate | Populates the specified Control object by using child controls from one of the ListView control templates. | .gif) | IsLiteralContent | Infrastructure. Determines if the server control holds only literal content. (Inherited from Control.) | .gif) | LoadControlState | Loads the state of the properties in the ListView control that must be persisted, even when the EnableViewState property is set to false. (Overrides Control..::.LoadControlState(Object).) | .gif) | LoadViewState | Loads the previously saved view state of the ListView control. (Overrides WebControl..::.LoadViewState(Object).) | .gif) | MapPathSecure | Retrieves the physical path that a virtual path, either absolute or relative, maps to. (Inherited from Control.) | .gif) | MarkAsDataBound | Sets the state of the control in view state as successfully bound to data. (Inherited from DataBoundControl.) | .gif) | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) | MergeStyle | 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.) | .gif) | OnBubbleEvent | Determines whether an event for the ListView control should be handled. (Overrides Control..::.OnBubbleEvent(Object, EventArgs).) | .gif) | OnDataBinding | Raises the DataBinding event. (Inherited from Control.) | .gif) | OnDataBound | Raises the DataBound event. (Inherited from BaseDataBoundControl.) | .gif) | OnDataPropertyChanged | Rebinds the data-bound control to its data after one of the base data source identification properties changes. (Inherited from DataBoundControl.) | .gif) | OnDataSourceViewChanged | Raises the DataSourceViewChanged event. (Inherited from DataBoundControl.) | .gif) | OnInit | Raises the Init event. (Overrides BaseDataBoundControl..::.OnInit(EventArgs).) | .gif) | OnItemCanceling | Raises the ItemCanceling event. | .gif) | OnItemCommand | Raises the ItemCommand event. | .gif) | OnItemCreated | Raises the ItemCreated event. | .gif) | OnItemDataBound | Raises the ItemDataBound event. | .gif) | OnItemDeleted | Raises the ItemDeleted event. | .gif) | OnItemDeleting | Raises the ItemDeleting event. | .gif) | OnItemEditing | Raises the ItemEditing event. | .gif) | OnItemInserted | Raises the ItemInserted event. | .gif) | OnItemInserting | Raises the ItemInserting event. | .gif) | OnItemUpdated | Raises the ItemUpdated event. | .gif) | OnItemUpdating | Raises the ItemUpdating event. | .gif) | OnLayoutCreated | Raises the LayoutCreated event. | .gif) | OnLoad | Handles the Control..::.Load event. (Inherited from DataBoundControl.) | .gif) | OnPagePreLoad | Sets the initialized state of the data-bound control before the control is loaded. (Inherited from DataBoundControl.) | .gif) | OnPagePropertiesChanged | Raises the PagePropertiesChanged event. | .gif) | OnPagePropertiesChanging | Raises the PagePropertiesChanging event. | .gif) | OnPreRender | Handles the PreRender event. (Inherited from BaseDataBoundControl.) | .gif) | OnSelectedIndexChanged | Raises the SelectedIndexChanged event. | .gif) | OnSelectedIndexChanging | Raises the SelectedIndexChanging event. | .gif) | OnSorted | Raises the Sorted event. | .gif) | OnSorting | Raises the Sorting event. | .gif) | OnTotalRowCountAvailable | Raises the IPageableItemContainer..::.TotalRowCountAvailable event. | .gif) | OnUnload | Raises the Unload event. (Inherited from Control.) | .gif) | OpenFile | Gets a Stream used to read a file. (Inherited from Control.) | .gif) | PerformDataBinding | Binds the ListView control to the specified data source. (Overrides DataBoundControl..::.PerformDataBinding(IEnumerable).) | .gif) | PerformSelect | Retrieves data from the associated data source. (Overrides DataBoundControl..::.PerformSelect()()().) | .gif) | RaiseBubbleEvent | Assigns any sources of the event and its information to the control's parent. (Inherited from Control.) | .gif) | RemovedControl | Called after a child control is removed from the Controls collection of the Control object. (Inherited from Control.) | .gif) | RemoveItems | Deletes all child controls in an item or group container of the ListView control. | .gif) | Render | Renders the Web server control content to the client's browser by using the specified HtmlTextWriter object. (Overrides WebControl..::.Render(HtmlTextWriter).) | .gif) | RenderBeginTag | Renders the HTML opening tag of the control to the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | RenderChildren | 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.) | .gif) | RenderContents | Renders the contents of the control to the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | 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.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object. (Inherited from Control.) | .gif) | RenderEndTag | Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | ResolveAdapter | Gets the control adapter responsible for rendering the specified control. (Inherited from Control.) | .gif) | ResolveClientUrl | Gets a URL that can be used by the browser. (Inherited from Control.) | .gif) | ResolveUrl | Converts a URL into one that is usable on the requesting client. (Inherited from Control.) | .gif) | SaveControlState | Saves the state of the properties in the ListView control that must be persisted, even when the EnableViewState property is set to false. (Overrides Control..::.SaveControlState()()().) | .gif) | SaveViewState | Saves the current view state of the ListView control. (Overrides WebControl..::.SaveViewState()()().) | .gif) | SelectItem | Selects the item that is in edit mode in a ListView control. | .gif) | SetDesignModeState | Sets design-time data for a control. (Inherited from Control.) | .gif) | SetEditItem | Sets the specified item into edit mode in a ListView control. | .gif) | SetPageProperties | Sets the properties of a page of data in the ListView control. | .gif) | SetRenderMethodDelegate | Infrastructure. Assigns an event handler delegate to render the server control and its content into its parent control. (Inherited from Control.) | .gif) | Sort | Sorts the ListView control, depending on the specified sort expression and direction. | .gif) | ToString | Returns a string that represents the current object. (Inherited from Object.) | .gif) | TrackViewState | Causes the control to track changes to its view state so they can be stored in the object's ViewState property. (Inherited from WebControl.) | .gif) | UpdateItem | Updates the record at the specified index in the data source. | .gif) | ValidateDataSource | Verifies that the object a data-bound control binds to is one it can work with. (Inherited from DataBoundControl.) | Top

Events
|
| Name | Description |
|---|
.gif) | DataBinding | Occurs when the server control binds to a data source. (Inherited from Control.) | .gif) | DataBound | Occurs after the server control binds to a data source. (Inherited from BaseDataBoundControl.) | .gif) | 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.) | .gif) | Init | Occurs when the server control is initialized, which is the first step in its lifecycle. (Inherited from Control.) | .gif) | ItemCanceling | Occurs when a cancel operation is requested, but before the ListView control cancels the insert or edit operation. | .gif) | ItemCommand | Occurs when a button in a ListView control is clicked. | .gif) | ItemCreated | Occurs when an item is created in a ListView control. | .gif) | ItemDataBound | Occurs when a data item is bound to data in a ListView control. | .gif) | ItemDeleted | Occurs when a delete operation is requested, after the ListView control deletes the item. | .gif) | ItemDeleting | Occurs when a delete operation is requested, but before the ListView control deletes the item. | .gif) | ItemEditing | Occurs when an edit operation is requested, but before the ListView item is put in edit mode. | .gif) | ItemInserted | Occurs when an insert operation is requested, after the ListView control has inserted the item in the data source. | .gif) | ItemInserting | Occurs when an insert operation is requested, but before the ListView control performs the insert. | .gif) | ItemUpdated | Occurs when an update operation is requested, after the ListView control updates the item. | .gif) | ItemUpdating | Occurs when an update operation is requested, but before the ListView control updates the item. | .gif) | LayoutCreated | Occurs when the LayoutTemplate template is created in a ListView control. | .gif) | Load | Occurs when the server control is loaded into the Page object. (Inherited from Control.) | .gif) | PagePropertiesChanged | Occurs when the page properties change, after the ListView control sets the new values. | .gif) | PagePropertiesChanging | Occurs when the page properties change, but before the ListView control sets the new values. | .gif) | PreRender | Occurs after the Control object is loaded but prior to rendering. (Inherited from Control.) | .gif) | SelectedIndexChanged | Occurs when an item's Select button is clicked, after the ListView control handles the select operation. | .gif) | SelectedIndexChanging | Occurs when an item's Select button is clicked, but before the ListView control handles the select operation. | .gif) | Sorted | Occurs when a sort operation is requested, after the ListView control handles the sort operation. | .gif) | Sorting | Occurs when a sort operation is requested, but before the ListView control handles the sort operation. | .gif) | Unload | Occurs when the server control is unloaded from memory. (Inherited from Control.) | Top

Extension Methods

Explicit Interface Implementations
|
| Name | Description |
|---|
.gif) .gif) | IAttributeAccessor..::.GetAttribute | Infrastructure. Gets an attribute of the Web control with the specified name. (Inherited from WebControl.) | .gif) .gif) | IAttributeAccessor..::.SetAttribute | Sets an attribute of the Web control to the specified name and value. (Inherited from WebControl.) | .gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | For a description of this member, see IControlBuilderAccessor..::.ControlBuilder. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.GetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.SetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. For a description of this member, see IControlDesignerAccessor..::.SetOwnerControl. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | For a description of this member, see IControlDesignerAccessor..::.UserData. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | For a description of this member, see IDataBindingsAccessor..::.DataBindings. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | For a description of this member, see IDataBindingsAccessor..::.HasDataBindings. (Inherited from Control.) | .gif) .gif) | IDataBoundControl..::.DataKeyNames | Gets or sets an array that contains the names of the primary-key fields of the items that are displayed in a data-bound control. | .gif) .gif) | IDataBoundControl..::.DataMember | Gets or sets the name of the list of data that the data-bound control binds to when the data source contains more than one distinct list of data items. | .gif) .gif) | IDataBoundControl..::.DataSource | Gets or sets the object from which a data-bound control retrieves its list of data items. | .gif) .gif) | IDataBoundControl..::.DataSourceID | Gets or sets the ID of the data source control from which a data-bound control retrieves its list of data items. | .gif) .gif) | IDataBoundControl..::.DataSourceObject | Gets an object that implements the IDataSource interface, which provides access to the object's data content. | .gif) .gif) | IDataBoundListControl..::.ClientIDRowSuffix | Gets the name of the data field whose value is used to uniquely identify each data row of a ListView control when the ClientIDMode property is set to Predictable. | .gif) .gif) | IDataBoundListControl..::.DataKeys | Gets a collection of data-key values that represent each row in a data-bound control. | .gif) .gif) | IDataBoundListControl..::.EnablePersistedSelection | Gets or sets the value that specifies whether a selected row persists when a user pages through data in a data-bound control. | .gif) .gif) | IDataBoundListControl..::.SelectedDataKey | Gets the data-key object that contains the data-key value for the selected row in a data-bound control. | .gif) .gif) | IDataBoundListControl..::.SelectedIndex | Gets or sets the index of the selected row in a data-bound control. | .gif) .gif) | IDataKeysControl..::.ClientIDRowSuffixDataKeys | Infrastructure. Gets a collection of the data values that are used to uniquely identify each instance of a data-bound control when ASP.NET generates the ClientID value. | .gif) .gif) | IExpressionsAccessor..::.Expressions | For a description of this member, see IExpressionsAccessor..::.Expressions. (Inherited from Control.) | .gif) .gif) | IExpressionsAccessor..::.HasExpressions | For a description of this member, see IExpressionsAccessor..::.HasExpressions. (Inherited from Control.) | .gif) .gif) | IPageableItemContainer..::.MaximumRows | Infrastructure. For a description of this member, see IPageableItemContainer..::.MaximumRows. | .gif) .gif) | IPageableItemContainer..::.SetPageProperties | Infrastructure. For a description of this member, see IPageableItemContainer..::.SetPageProperties. | .gif) .gif) | IPageableItemContainer..::.StartRowIndex | Infrastructure. For a description of this member, see IPageableItemContainer..::.StartRowIndex. | .gif) .gif) | IPageableItemContainer..::.TotalRowCountAvailable | Infrastructure. For a description of this member, see IPageableItemContainer..::.TotalRowCountAvailable. | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | For a description of this member, see IParserAccessor..::.AddParsedSubObject. (Inherited from Control.) | .gif) .gif) | IPersistedSelector..::.DataKey | Gets or sets the data-key value for the selected record in a data-bound control. | Top

Remarks
In this topic: IntroductionThe ListView control is used to display the values from a data source. It resembles the GridView control, except that it displays data by using user-defined templates instead of row fields. Creating your own templates gives you more flexibility in controlling how the data is displayed. A Visual Studio project with source code is available to accompany this topic: Download. The ListView control supports the following features: Support for binding to data source controls such as SqlDataSource, LinqDataSource, and ObjectDataSource. Customizable appearance through user-defined templates and styles. Built-in sorting capabilities. Built-in update and delete capabilities. Built-in insert capabilities. Support for paging capabilities by using a DataPager control. Built-in item selection capabilities. Programmatic access to the ListView object model to dynamically set properties, handle events, and so on. Multiple key fields.
To learn about other data-bound controls that are available in ASP.NET, see ASP.NET Data-Bound Web Server Controls Overview. TemplatesIn order for the ListView control to display content, you must create templates for different parts of the control. The ItemTemplate is required. All other templates are optional. The LayoutTemplate property is not required. However, you must create a template for the mode in which the control is configured. For example, a ListView control that supports inserting records must have an InsertItemTemplate template defined. The following table lists the templates that you can create for the ListView control. Template type | Description |
|---|
LayoutTemplate
| The root template that defines a container object, such as a table, div, or span element, that will contain the content defined in the ItemTemplate or GroupTemplate template. It might also contain a DataPager object. |
ItemTemplate
| Defines the data-bound content to display for individual items. |
ItemSeparatorTemplate
| Defines the content to render between individual items. |
GroupTemplate
| Defines a container object, such as a table row (tr), div, or span element, that will contain the content defined in the ItemTemplate and EmptyItemTemplate templates. The number of items that are displayed in a group is specified by the GroupItemCount property. |
GroupSeparatorTemplate
| Defines the content to render between groups of items. |
EmptyItemTemplate
| Defines the content to render for an empty item when a GroupTemplate template is used. For example, if the GroupItemCount property is set to 5, and the total number of items returned from the data source is 8, the last group of data displayed by the ListView control will contain three items as specified by the ItemTemplate template, and two items as specified by the EmptyItemTemplate template. |
EmptyDataTemplate
| Defines the content to render if the data source returns no data. |
SelectedItemTemplate
| Defines the content to render for the selected data item to differentiate the selected item from other items. |
AlternatingItemTemplate
| Defines the content to render for alternating items to make it easier to distinguish between consecutive items. |
EditItemTemplate
| Defines the content to render when an item is being edited. The EditItemTemplate template is rendered in place of the ItemTemplate template for the data item that is being edited. |
InsertItemTemplate
| Defines the content to render to insert an item. The InsertItemTemplate template is rendered in place of an ItemTemplate template at either the start or at the end of the items that are displayed by the ListView control. You can specify where the InsertItemTemplate template is rendered by using the InsertItemPosition property of the ListView control. |
To display the value of a field in a template such as ItemTemplate, you use a data-binding expression. For more information about data-binding expressions, see Data-Binding Expressions Overview. To bind input controls in the EditItemTemplate and InsertItemTemplate templates to fields of a data source, you can use two-way binding expressions. This enables the ListView control to automatically extract the values of the input control for an update or insert operation. Two-way binding expressions also enable input controls in an EditItemTemplate to automatically display the original field values. For more information about two-way binding expressions, see Binding to Databases. Binding to a Data SourceYou can bind the ListView control to a data source control (such as the SqlDataSource control or ObjectDataSource control) 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<(Of <(T>)>), or other collection types. Use one of the following methods to bind the ListView control to the appropriate data source type: To bind to a data source control, set the DataSourceID property of the ListView control to the ID value of the data source control. The ListView control automatically binds to the specified data source control and can take advantage of the data source control's capabilities to perform sorting, 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 ListView control to the data source, and then call the DataBind method. When you use this technique, the ListView control does not provide built-in sorting, updating, deleting, and paging functionality. You must provide this functionality by using the appropriate event.
For more information about data binding, see ASP.NET Data Access. Note |
|---|
The ListView 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 you display it in the application. We strongly recommend that values be HTML-encoded whenever possible before they are displayed in this control. ASP.NET provides an input request validation feature to help block script and HTML in user input. You can also use validation server controls to check user input. For more information, see Introduction to the Validation Controls. |
Data OperationsWhen the ListView control is bound to a data source control, the ListView control can take advantage of the data source control's capabilities and provide automatic sort, insert, update, and delete functionality. Note |
|---|
The ListView control can provide support for sorting, inserting, updating, and deleting with other types of data sources. However, in order to implement these operations, you must create code in an appropriate event handler. |
Because the ListView control uses templates, it does not provide a way to automatically generate buttons to perform update, delete, insert, sort, or select operations. You must manually include these buttons in the appropriate template. The ListView control recognizes certain buttons whose CommandName property is set to a specific value. The following table lists the buttons that the ListView control recognizes and their functions. Unlike the Delete button (which deletes the current data item immediately), when the Edit button is clicked, the ListView control displays the current item in edit mode. In edit mode, the content that is contained in the EditItemTemplate property is displayed for the current data item. Typically, in the edit item template, 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 CheckBox control) also usually display a field's value for a user to modify. Clicking the Update button updates the record in the data source, and clicking the Cancel button cancels the edit operation. The insert functionality is enabled when the InsertItemPosition property is set to FirstItem or LastItem. This property defines where the InsertItemTemplate template is rendered for the insert item. The insert item template typically includes an Insert and a Cancel button, and empty input controls are displayed for users to enter the values for the new record. Clicking the Insert button inserts the record in the data source, and clicking the Cancel button clears all the fields. SortingThe ListView control enables users to sort the items by clicking the Sort button. Sort functionality is defined in the CommandArgument property of the button that contains the columns to be sorted. PagingInstead of displaying all the records from the data source at the same time, the ListView control can break the records into pages. To enable paging, associate a DataPager control with the ListView control. Then insert a DataPager control inside the LayoutTemplate template. Alternatively, if the DataPager control is outside the ListView control, set the PagedControlID property to the ID of the ListView control. EventsThe following table lists the events that are supported by the ListView control. Event | Description |
|---|
ItemCanceling
| Occurs when the Cancel button (a button with its CommandName property set to "Cancel") is clicked, but before the ListView control cancels the insert or edit operation. This event is often used to stop the cancel operation. |
ItemCommand
| Occurs when a button is clicked in the ListView control. This event is often used to perform a custom task when a button is clicked in the control. |
ItemCreated
| Occurs when a new item is created in the ListView control. This event is often used to modify the content of an item when the item is created. |
ItemDataBound
| Occurs when a data item is bound to data in the ListView control. This event is often used to modify the content of an item when the item is bound to data. |
ItemDeleted
| Occurs when a Delete button (a button with its CommandName property set to "Delete") is clicked or the DeleteItem method is called, after the ListView 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 (a button with its CommandName property set to "Delete") is clicked or the DeleteItem method is called, but before the ListView control deletes the record from the data source. This event is often used to confirm or cancel the delete operation. |
ItemEditing
| Occurs when an Edit button (a button with its CommandName property set to "Edit") is clicked, but before the ListView control enters edit mode. This event is often used to cancel the editing operation. |
ItemInserted
| Occurs when an Insert button (a button with its CommandName property set to "Insert") is clicked or the InsertNewItem method is called, after the ListView control inserts the new record from the data source. This event is often used to check the results of the insert operation. |
ItemInserting
| Occurs when an Insert button (a button with its CommandName property set to "Insert") is clicked or the InsertNewItem method is called, but before the ListView control inserts the record. This event is often used to cancel the insert operation or change or validate the values of the new item. |
ItemUpdated
| Occurs when an Update button (a button with its CommandName property set to "Update") is clicked or the UpdateItem method is called, after the ListView control updates the record. This event is often used to check the results of the update operation. |
ItemUpdating
| Occurs when an Update button (a button with its CommandName property set to "Update") is clicked or the UpdateItem method is called, but before the ListView control updates the record. This event is often used to cancel the updating operation or change or validate the values of the edited item. |
LayoutCreated
| Occurs when the LayoutTemplate template is created in a ListView control. This event is often used to perform a task after the template is created. |
PagePropertiesChanged
| Occurs when the page properties change, after the ListView control sets the new values. |
PagePropertiesChanging
| Occurs when the data-page properties change, but before the ListView control sets the new values. |
SelectedIndexChanged
| Occurs when a Select button (a button with its CommandName property set to "Select") is clicked, after the ListView control handles the select operation. This event is often used to perform a custom task after an item is selected in the control. |
SelectedIndexChanging
| Occurs when a Select button (a button with its CommandName property set to "Select") is clicked, but before the ListView control handles the select operation. This event is often used to cancel the select operation. |
Sorted
| Occurs when a Sort button (a button with its CommandName property set to "Sort") is clicked or the Sort method is called, after the ListView control handles the sort operation. This event is typically used to perform a custom task after a user clicks a Sort button and the data has been sorted. |
Sorting
| Occurs when a Sort button (a button with its CommandName property set to "Sort") is clicked or the Sort method is called, but before the ListView control handles the sort operation. This event is often used to cancel the sorting operation or to perform a custom sorting routine. |
Declarative Syntax
<asp:ListView
ConvertEmptyStringToNull="True|False"
DataKeyNames="string"
DataMember="string"
DataSource="string"
DataSourceID="string"
EditIndex="integer"
Enabled="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
GroupPlaceholderID="string"
GroupItemCount="integer"
ID="string"
InsertItemPosition="None|FirstItem|LastItem"
ItemPlaceholderID="string"
OnDataBinding="DataBinding event handler"
OnDataBound="DataBound event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnItemCanceling="ItemCanceling event handler"
OnItemCommand="ItemCommand event handler"
OnItemCreated="ItemCreated event handler"
OnItemDataBound="ItemDataBound event handler"
OnItemDeleted="ItemDeleted event handler"
OnItemDeleting="ItemDeleting event handler"
OnItemEditing="ItemEditing event handler"
OnItemInserted="ItemInserted event handler"
OnItemInserting="ItemInserting event handler"
OnItemUpdated="ItemUpdated event handler"
OnItemUpdating="ItemUpdating event handler"
OnLayoutCreated="LayoutCreated event handler"
OnLoad="Load event handler"
OnPagePropertiesChanged="PagePropertiesChanged event handler"
OnPagePropertiesChanging="PagePropertiesChanging event handler"
OnPreRender="PreRender event handler"
OnSelectedIndexChanged="SelectedIndexChanged event handler"
OnSelectedIndexChanging="SelectedIndexChanging event handler"
OnSorted="Sorted event handler"
OnSorting="Sorting event handler"
OnUnload="Unload event handler"
runat="server"
SelectedIndex="integer"
SkinID="string"
Style="string"
Visible="True|False"
>
<AlternatingItemTemplate>
<!-- child controls -->
</AlternatingItemTemplate>
<EditItemTemplate>
<!-- child controls -->
</EditItemTemplate>
<EmptyDataTemplate>
<!-- child controls -->
</EmptyDataTemplate>
<EmptyItemTemplate>
<!-- child controls -->
</EmptyItemTemplate>
<GroupSeparatorTemplate>
<!-- child controls -->
</GroupSeparatorTemplate>
<GroupTemplate>
<!-- child controls -->
</GroupTemplate>
<InsertItemTemplate>
<!-- child controls -->
</InsertItemTemplate>
<ItemSeparatorTemplate>
<!-- child controls -->
</ItemSeparatorTemplate>
<ItemTemplate>
<!-- child controls -->
</ItemTemplate>
<LayoutTemplate>
<!-- child controls -->
</LayoutTemplate>
<SelectedItemTemplate>
<!-- child controls -->
</SelectedItemTemplate>
</asp:ListView>

Examples
The following example shows how to use the ListView control to display records from a database by using an HTML table. The values are retrieved by using a LinqDataSource control.
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<asp:ListView ID="VendorsListView"
DataSourceID="VendorsDataSource"
DataKeyNames="VendorID"
runat="server">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" ID="tbl1" runat="server">
<tr runat="server" style="background-color: #98FB98">
<th runat="server">ID</th>
<th runat="server">Account Number</th>
<th runat="server">Name</th>
<th runat="server">Preferred Vendor</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("VendorID") %>' />
</td>
<td>
<asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("AccountNumber") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' /></td>
<td>
<asp:CheckBox ID="PreferredCheckBox" runat="server"
Checked='<%# Eval("PreferredVendorStatus") %>' Enabled="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Add a LINQ -->
<!-- to SQL class to the project to map to a table in -->
<!-- the database. -->
<asp:LinqDataSource ID="VendorsDataSource" runat="server"
ContextTypeName="AdventureWorksClassesDataContext"
Select="new (VendorID, AccountNumber, Name, PreferredVendorStatus)"
TableName="Vendors" Where="ActiveFlag == @ActiveFlag">
<WhereParameters>
<asp:Parameter DefaultValue="true" Name="ActiveFlag" Type="Boolean" />
</WhereParameters>
</asp:LinqDataSource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<asp:ListView ID="VendorsListView"
DataSourceID="VendorsDataSource"
DataKeyNames="VendorID"
runat="server">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" ID="tbl1" runat="server">
<tr runat="server" style="background-color: #98FB98">
<th runat="server">ID</th>
<th runat="server">Account Number</th>
<th runat="server">Name</th>
<th runat="server">Preferred Vendor</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("VendorID") %>' />
</td>
<td>
<asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("AccountNumber") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' /></td>
<td>
<asp:CheckBox ID="PreferredCheckBox" runat="server"
Checked='<%# Eval("PreferredVendorStatus") %>' Enabled="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Add a LINQ -->
<!-- to SQL class to the project to map to a table in -->
<!-- the database. -->
<asp:LinqDataSource ID="VendorsDataSource" runat="server"
ContextTypeName="AdventureWorksClassesDataContext"
Select="new (VendorID, AccountNumber, Name, PreferredVendorStatus)"
TableName="Vendors" Where="ActiveFlag == @ActiveFlag">
<WhereParameters>
<asp:Parameter DefaultValue="true" Name="ActiveFlag" Type="Boolean" />
</WhereParameters>
</asp:LinqDataSource>
</form>
</body>
</html>
The following example shows how to use the ListView control to display values in a flow layout by using the div element. The values are retrieved by using a SqlDataSource control.
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Flow Layout Example</title>
<style type="text/css">
.plainBox {
font-family: Verdana, Arial, sans-serif;
font-size: 11px;
background: #ffffff;
border:1px solid #336666;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Flow Layout Example</h3>
Select the color:
<asp:DropDownList ID="ColorList" runat="server"
AutoPostBack="True"
DataSourceID="ColorDataSource"
DataTextField="Color"
DataValueField="Color">
</asp:DropDownList><br /><br />
<asp:ListView runat="server" ID="ProductListView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID">
<LayoutTemplate>
<div runat="server" id="lstProducts">
<div runat="server" id="itemPlaceholder" />
</div>
<asp:DataPager ID="DataPager1" runat="server" PageSize="5" >
<Fields>
<asp:NextPreviousPagerField
ButtonType="Button"
ShowFirstPageButton="True"
ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<asp:Image ID="ProductImage" runat="server"
ImageUrl='<%# "~/images/thumbnails/" & Eval("ThumbnailPhotoFileName") %>' />
<div class="plainBox" runat="server">
<asp:HyperLink ID="ProductLink" runat="server" Text='<%# Eval("Name") %>'
NavigateUrl='<%# "ProductDetails.aspx?productID=" & Eval("ProductID") %>' />
<br /><br />
<b>Price:</b>
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("ListPrice", "{0:c}")%>' /> <br />
</div>
<br />
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource ID="ProductsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT P.ProductID, P.Name, P.Color, P.ListPrice,
PF.ThumbnailPhotoFileName, P.Size
FROM Production.Product AS P
INNER JOIN Production.ProductProductPhoto AS PPF ON P.ProductID = PPF.ProductID
INNER JOIN Production.ProductPhoto AS PF ON PPF.ProductPhotoID = PF.ProductPhotoID
WHERE P.Color = @Color" >
<SelectParameters>
<asp:ControlParameter ControlID="ColorList" Name="Color"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="ColorDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT DISTINCT Color FROM Production.Product">
</asp:SqlDataSource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Flow Layout Example</title>
<style type="text/css">
.plainBox {
font-family: Verdana, Arial, sans-serif;
font-size: 11px;
background: #ffffff;
border:1px solid #336666;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Flow Layout Example</h3>
Select the color:
<asp:DropDownList ID="ColorList" runat="server"
AutoPostBack="True"
DataSourceID="ColorDataSource"
DataTextField="Color"
DataValueField="Color">
</asp:DropDownList><br /><br />
<asp:ListView runat="server" ID="ProductListView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID">
<LayoutTemplate>
<div runat="server" id="lstProducts">
<div runat="server" id="itemPlaceholder" />
</div>
<asp:DataPager runat="server" PageSize="5" >
<Fields>
<asp:NextPreviousPagerField
ButtonType="Button"
ShowFirstPageButton="True"
ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<asp:Image ID="ProductImage" runat="server"
ImageUrl='<%# "~/images/thumbnails/" + Eval("ThumbnailPhotoFileName") %>' />
<div class="plainBox" runat="server">
<asp:HyperLink ID="ProductLink" runat="server" Text='<%# Eval("Name") %>'
NavigateUrl='<%# "ProductDetails.aspx?productID=" + Eval("ProductID") %>' />
<br /><br />
<b>Price:</b>
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("ListPrice", "{0:c}")%>' /> <br />
</div>
<br />
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource ID="ProductsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT P.ProductID, P.Name, P.Color, P.ListPrice,
PF.ThumbnailPhotoFileName, P.Size
FROM Production.Product AS P
INNER JOIN Production.ProductProductPhoto AS PPF ON P.ProductID = PPF.ProductID
INNER JOIN Production.ProductPhoto AS PF ON PPF.ProductPhotoID = PF.ProductPhotoID
WHERE P.Color = @Color" >
<SelectParameters>
<asp:ControlParameter ControlID="ColorList" Name="Color"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="ColorDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT DISTINCT Color FROM Production.Product">
</asp:SqlDataSource>
</form>
</body>
</html>
The following example shows how to use the ListView control to insert, delete, and update records. Security Note |
|---|
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="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Example</title>
<style type="text/css">
.EditItem { background-color:#8FBC8F;}
.SelectedItem { background-color:#9ACD32; }
.InsertItem { background-color:#FFFACD;}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<h5>Departments</h5>
<asp:ListView ID="DepartmentsListView"
DataSourceID="DepartmentsDataSource"
DataKeyNames="DepartmentID"
ConvertEmptyStringToNull="true"
InsertItemPosition="LastItem"
runat="server">
<LayoutTemplate>
<table cellpadding="2" runat="server" id="tblDepartments" width="640px" cellspacing="0">
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select" />
<asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
</td>
<td>
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
</td>
<td>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr class="SelectedItem" runat="server">
<td>
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" />
<asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
</td>
<td>
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
</td>
<td>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
</td>
</tr>
</SelectedItemTemplate>
<EditItemTemplate>
<tr class="EditItem">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<b>ID</b><br />
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox"
Text="Name" Font-Bold="true"/><br />
<asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' />
</td>
<td>
<asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox"
Text="Group Name" Font-Bold="true" /><br />
<asp:TextBox ID="GroupNameTextBox" runat="server"
Width="200px"
Text='<%#Bind("GroupName") %>' />
<br />
</td>
</tr>
</EditItemTemplate>
<InsertItemTemplate>
<tr class="InsertItem">
<td colspan="2">
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox"
Text="Name" Font-Bold="true"/><br />
<asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' /><br />
</td>
<td>
<asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox"
Text="Group Name" Font-Bold="true" /><br />
<asp:TextBox ID="GroupNameTextBox" runat="server" Text='<%#Bind("GroupName") %>' />
</td>
</tr>
</InsertItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource ID="DepartmentsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department"
UpdateCommand="UPDATE HumanResources.Department
SET Name = @Name, GroupName = @GroupName WHERE (DepartmentID = @DepartmentID)"
DeleteCommand="DELETE FROM HumanResources.Department
WHERE (DepartmentID = @DepartmentID)"
InsertCommand="INSERT INTO HumanResources.Department(Name, GroupName)
VALUES (@Name, @GroupName)">
</asp:SqlDataSource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Example</title>
<style type="text/css">
.EditItem { background-color:#8FBC8F;}
.SelectedItem { background-color:#9ACD32; }
.InsertItem { background-color:#FFFACD;}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<h5>Departments</h5>
<asp:ListView ID="DepartmentsListView"
DataSourceID="DepartmentsDataSource"
DataKeyNames="DepartmentID"
ConvertEmptyStringToNull="true"
InsertItemPosition="LastItem"
runat="server">
<LayoutTemplate>
<table cellpadding="2" runat="server" id="tblDepartments" width="640px" cellspacing="0">
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select" />
<asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
</td>
<td>
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
</td>
<td>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr class="SelectedItem" runat="server">
<td>
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" />
<asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
</td>
<td>
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
</td>
<td>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
</td>
</tr>
</SelectedItemTemplate>
<EditItemTemplate>
<tr class="EditItem">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<b>ID</b><br />
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox"
Text="Name" Font-Bold="true"/><br />
<asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' />
</td>
<td>
<asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox"
Text="Group Name" Font-Bold="true" /><br />
<asp:TextBox ID="GroupNameTextBox" runat="server"
Width="200px"
Text='<%#Bind("GroupName") %>' />
<br />
</td>
</tr>
</EditItemTemplate>
<InsertItemTemplate>
<tr class="InsertItem">
<td colspan="2">
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox"
Text="Name" Font-Bold="true"/><br />
<asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' /><br />
</td>
<td>
<asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox"
Text="Group Name" Font-Bold="true" /><br />
<asp:TextBox ID="GroupNameTextBox" runat="server" Text='<%#Bind("GroupName") %>' />
</td>
</tr>
</InsertItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource ID="DepartmentsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department"
UpdateCommand="UPDATE HumanResources.Department
SET Name = @Name, GroupName = @GroupName WHERE (DepartmentID = @DepartmentID)"
DeleteCommand="DELETE FROM HumanResources.Department
WHERE (DepartmentID = @DepartmentID)"
InsertCommand="INSERT INTO HumanResources.Department(Name, GroupName)
VALUES (@Name, @GroupName)">
</asp:SqlDataSource>
</form>
</body>
</html>

Version Information
.NET FrameworkSupported in: 4, 3.5

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Bibliothèque de classes .NET Framework ListView, classe Affiche les valeurs d'une source de données à l'aide de modèles définis par l'utilisateur. Le contrôle ListView permet aux utilisateurs de sélectionner, trier, supprimer, modifier et insérer des enregistrements.

Hiérarchie d'héritage
Espace de noms :
System.Web.UI.WebControls
Assembly :
System.Web.Extensions (dans System.Web.Extensions.dll)

Syntaxe
<ControlValuePropertyAttribute("SelectedValue")> _
<ToolboxBitmapAttribute(GetType(ListView), "ListView.bmp")> _
Public Class ListView _
Inherits DataBoundControl _
Implements INamingContainer, IPageableItemContainer, IPersistedSelector, IDataKeysControl, _
IDataBoundListControl, IDataBoundControl
[ControlValuePropertyAttribute("SelectedValue")]
[ToolboxBitmapAttribute(typeof(ListView), "ListView.bmp")]
public class ListView : DataBoundControl, INamingContainer,
IPageableItemContainer, IPersistedSelector, IDataKeysControl, IDataBoundListControl, IDataBoundControl
[ControlValuePropertyAttribute(L"SelectedValue")]
[ToolboxBitmapAttribute(typeof(ListView), L"ListView.bmp")]
public ref class ListView : public DataBoundControl,
INamingContainer, IPageableItemContainer, IPersistedSelector, IDataKeysControl, IDataBoundListControl,
IDataBoundControl
[<ControlValuePropertyAttribute("SelectedValue")>]
[<ToolboxBitmapAttribute(typeof(ListView), "ListView.bmp")>]
type ListView =
class
inherit DataBoundControl
interface INamingContainer
interface IPageableItemContainer
interface IPersistedSelector
interface IDataKeysControl
interface IDataBoundListControl
interface IDataBoundControl
end
Le type ListView expose les membres suivants.

Constructeurs
|
| Nom | Description |
|---|
.gif) | ListView | Initialise une nouvelle instance de la classe ListView. | Début

Méthodes
|
| Nom | Description |
|---|
.gif) | AddAttributesToRender | Ajoute des attributs et des styles HTML qui doivent être rendus au HtmlTextWriterTag spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | AddControlToContainer | Ajoute le contrôle spécifié au conteneur spécifié. | .gif) | AddedControl | Appelée après l'ajout d'un contrôle enfant à la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | AddParsedSubObject | Avertit le contrôle serveur qu'un élément XML ou HTML a été analysé et l'ajoute à l'objet ControlCollection du contrôle serveur. (Hérité de Control.) | .gif) | ApplyStyle | Copie tous les éléments non vides du style spécifié vers le contrôle Web, en remplaçant les éléments de style existants du contrôle. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | ApplyStyleSheetSkin | Applique les propriétés de style définies dans la feuille de style de la page au contrôle. (Hérité de Control.) | .gif) | BuildProfileTree | Infrastructure. Collecte des informations sur le contrôle serveur et les livre à la propriété Trace à afficher lorsque le traçage est activé pour la page. (Hérité de Control.) | .gif) | ClearCachedClientID | Infrastructure. Affecte à la valeur ClientID mise en cache la valeur nullNothingnullptrune référence null (Nothing en Visual Basic). (Hérité de Control.) | .gif) | ClearChildControlState | Supprime les informations sur l'état du contrôle des contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearChildState | Supprime les informations sur l'état d'affichage et sur l'état du contrôle de tous les contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearChildViewState | Supprime les informations d'état d'affichage de tous les contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearEffectiveClientIDMode | Infrastructure. Affecte la valeur Inherit à la propriété ClientIDMode de l'instance de contrôle actuelle et de tous contrôles enfants. (Hérité de Control.) | .gif) | ConfirmInitState | Définit l'état initialisé du contrôle lié aux données. (Hérité de BaseDataBoundControl.) | .gif) | CopyBaseAttributes | Copie les propriétés non encapsulées par l'objet Style du contrôle serveur Web spécifié vers le contrôle serveur Web à partir duquel cette méthode est appelée. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | CreateChildControls()()() | Crée la hiérarchie des contrôles utilisée pour restituer le contrôle ListView, basé sur les valeurs qui sont stockées dans l'état d'affichage. (Substitue Control..::.CreateChildControls()()().) | .gif) | CreateChildControls(IEnumerable, Boolean) | Crée la hiérarchie des contrôles qui est utilisée pour restituer le contrôle ListView à l'aide de la source de données spécifiée. | .gif) | CreateControlCollection | Crée un nouvel objet ControlCollection pour contenir les contrôles enfants (littéraux et serveur) du contrôle serveur. (Hérité de Control.) | .gif) | CreateControlStyle | Crée le style par défaut du contrôle. (Substitue WebControl..::.CreateControlStyle()()().) | .gif) | CreateDataItem | Crée un élément de données dans le contrôle ListView. | .gif) | CreateDataSourceSelectArguments | Crée l'objet DataSourceSelectArguments qui contient les arguments passés à la source de données. (Substitue DataBoundControl..::.CreateDataSourceSelectArguments()()().) | .gif) | CreateEmptyDataItem | Crée le modèle EmptyDataTemplate dans le contrôle ListView. | .gif) | CreateEmptyItem | Crée un élément vide dans le contrôle ListView. | .gif) | CreateInsertItem | Crée un élément d'insertion dans le contrôle ListView. | .gif) | CreateItem | Crée un objet ListViewItem avec le type spécifié. | .gif) | CreateItemsInGroups | Crée la hiérarchie des contrôles ListView dans des groupes. | .gif) | CreateItemsWithoutGroups | Crée la hiérarchie des contrôles ListView sans groupes. | .gif) | CreateLayoutTemplate | Crée le conteneur racine dans le contrôle ListView. | .gif) | CreateSuffixArrayList | Infrastructure. Crée un tableau de suffixes pour qu'ASP.NET l'utilise lorsqu'il génère la valeur ClientID. | .gif) | DataBind()()() | Lie une source de données au contrôle serveur appelé et à tous ses contrôles enfants. (Hérité de BaseDataBoundControl.) | .gif) | DataBind(Boolean) | Lie une source de données au contrôle serveur appelé et tous ses contrôles enfants avec une option pour déclencher l'événement DataBinding. (Hérité de Control.) | .gif) | DataBindChildren | Lie une source de données aux contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | DeleteItem | Supprime l'enregistrement à l'index spécifié de la source de données. | .gif) | Dispose | Permet à un contrôle serveur d'effectuer le nettoyage final avant qu'il soit libéré de la mémoire. (Hérité de Control.) | .gif) | EnsureChildControls | Détermine si le contrôle serveur contient des contrôles enfants. S'il ne contient pas de contrôles enfants, il en crée. (Hérité de Control.) | .gif) | EnsureDataBound | Appelle la méthode DataBind si la propriété DataSourceID est définie et que le contrôle lié aux données est marqué pour demander à être lié. (Hérité de BaseDataBoundControl.) | .gif) | EnsureID | Crée un identificateur pour les contrôles auxquels aucun identificateur n'est assigné. (Hérité de Control.) | .gif) | EnsureLayoutTemplate | Garantit que le contenu LayoutTemplate est créé correctement dans le contrôle ListView. | .gif) | Equals(Object) | Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.) | .gif) | ExtractItemValues | Récupère les valeurs de chaque champ déclarées dans l'élément spécifié et les stocke dans l'objet IOrderedDictionary spécifié. | .gif) | Finalize | Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de netto***ge avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.) | .gif) | FindControl(String) | Recherche un contrôle serveur possédant le paramètre id spécifié dans le conteneur d'attribution de noms actuel. (Hérité de Control.) | .gif) | FindControl(String, Int32) | Infrastructure. Recherche le conteneur d'attribution de noms actuel d'un contrôle serveur avec l'id spécifié et un entier, spécifié dans le paramètre pathOffset, qui facilite la recherche. Vous ne devez pas substituer cette version de la méthode FindControl. (Hérité de Control.) | .gif) | FindPlaceholder | Recherche le conteneur spécifié pour un contrôle qui possède l'identificateur spécifié. | .gif) | Focus | Affecte le focus d'entrée à un contrôle. (Hérité de Control.) | .gif) | GetData | Récupère un objet DataSourceView que le contrôle lié aux données utilise pour exécuter des opérations de données. (Hérité de DataBoundControl.) | .gif) | GetDataSource | Récupère l'interface IDataSource à laquelle le contrôle lié aux données est associé, le cas échéant. (Hérité de DataBoundControl.) | .gif) | GetDesignModeState | Infrastructure. Obtient les données au moment du design pour un contrôle. (Hérité de Control.) | .gif) | GetHashCode | Sert de fonction de hachage pour un type particulier. (Hérité de Object.) | .gif) | GetRouteUrl(Object) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(RouteValueDictionary) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(String, Object) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire et à un nom d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(String, RouteValueDictionary) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire et à un nom d'itinéraire. (Hérité de Control.) | .gif) | GetType | Obtient le Type de l'instance actuelle. (Hérité de Object.) | .gif) | GetUniqueIDRelativeTo | Retourne la partie préfixée de la propriété UniqueID du contrôle spécifié. (Hérité de Control.) | .gif) | HasControls | Détermine si le contrôle serveur contient des contrôles enfants. (Hérité de Control.) | .gif) | HasEvents | Retourne une valeur indiquant si des événements sont inscrits pour le contrôle ou des contrôles enfants. (Hérité de Control.) | .gif) | InsertNewItem | Insère l'enregistrement actif dans la source de données. | .gif) | InstantiateEmptyDataTemplate | Remplit l'objet Control spécifié en utilisant les contrôles enfants contenus dans le modèle EmptyDataTemplate. | .gif) | InstantiateEmptyItemTemplate | Remplit l'objet Control spécifié en utilisant les contrôles enfants contenus dans le modèle EmptyItemTemplate. | .gif) | InstantiateGroupSeparatorTemplate | Remplit l'objet Control spécifié en utilisant les contrôles enfants contenus dans le modèle GroupSeparatorTemplate. | .gif) | InstantiateGroupTemplate | Remplit l'objet Control spécifié en utilisant les contrôles enfants contenus dans le modèle GroupTemplate. | .gif) | InstantiateInsertItemTemplate | Remplit l'objet Control spécifié en utilisant les contrôles enfants contenus dans le modèle InsertItemTemplate. | .gif) | InstantiateItemSeparatorTemplate | Remplit l'objet Control spécifié en utilisant les contrôles enfants contenus dans le modèle ItemSeparatorTemplate. | .gif) | InstantiateItemTemplate | Remplit l'objet Control spécifié en utilisant des contrôles enfants de l'un des modèles de contrôle ListView. | .gif) | IsLiteralContent | Infrastructure. Détermine si le contrôle serveur ne détient qu'un contenu littéral. (Hérité de Control.) | .gif) | LoadControlState | Charge l'état des propriétés dans le contrôle ListView à faire persister, même lorsque la propriété EnableViewState a la valeur false. (Substitue Control..::.LoadControlState(Object).) | .gif) | LoadViewState | Charge l'état d'affichage précédemment enregistré du contrôle ListView. (Substitue WebControl..::.LoadViewState(Object).) | .gif) | MapPathSecure | Récupère le chemin d'accès physique auquel un chemin d'accès virtuel, absolu ou relatif, correspond. (Hérité de Control.) | .gif) | MarkAsDataBound | Définit l'état du contrôle dans l'état d'affichage comme lié avec succès aux données. (Hérité de DataBoundControl.) | .gif) | MemberwiseClone | Crée une copie superficielle de l'objet Object actif. (Hérité de Object.) | .gif) | MergeStyle | Copie tous les éléments non vides du style spécifié vers le contrôle Web, mais ne remplace aucun élément de style existant du contrôle. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | OnBubbleEvent | Détermine si un événement pour le contrôle ListView doit être géré. (Substitue Control..::.OnBubbleEvent(Object, EventArgs).) | .gif) | OnDataBinding | Déclenche l'événement DataBinding. (Hérité de Control.) | .gif) | OnDataBound | Déclenche l'événement DataBound. (Hérité de BaseDataBoundControl.) | .gif) | OnDataPropertyChanged | Relie le contrôle lié aux données à ses données après la modification d'une des propriétés de l'identification de la source de données de base. (Hérité de DataBoundControl.) | .gif) | OnDataSourceViewChanged | Déclenche l'événement DataSourceViewChanged. (Hérité de DataBoundControl.) | .gif) | OnInit | Déclenche l'événement Init. (Substitue BaseDataBoundControl..::.OnInit(EventArgs).) | .gif) | OnItemCanceling | Déclenche l'événement ItemCanceling. | .gif) | OnItemCommand | Déclenche l'événement ItemCommand. | .gif) | OnItemCreated | Déclenche l'événement ItemCreated. | .gif) | OnItemDataBound | Déclenche l'événement ItemDataBound. | .gif) | OnItemDeleted | Déclenche l'événement ItemDeleted. | .gif) | OnItemDeleting | Déclenche l'événement ItemDeleting. | .gif) | OnItemEditing | Déclenche l'événement ItemEditing. | .gif) | OnItemInserted | Déclenche l'événement ItemInserted. | .gif) | OnItemInserting | Déclenche l'événement ItemInserting. | .gif) | OnItemUpdated | Déclenche l'événement ItemUpdated. | .gif) | OnItemUpdating | Déclenche l'événement ItemUpdating. | .gif) | OnLayoutCreated | Déclenche l'événement LayoutCreated. | .gif) | OnLoad | Gère l'événement Control..::.Load. (Hérité de DataBoundControl.) | .gif) | OnPagePreLoad | Définit l'état initialisé du contrôle lié aux données avant que le contrôle ne soit chargé. (Hérité de DataBoundControl.) | .gif) | OnPagePropertiesChanged | Déclenche l'événement PagePropertiesChanged. | .gif) | OnPagePropertiesChanging | Déclenche l'événement PagePropertiesChanging. | .gif) | OnPreRender | Gère l'événement PreRender. (Hérité de BaseDataBoundControl.) | .gif) | OnSelectedIndexChanged | Déclenche l'événement SelectedIndexChanged. | .gif) | OnSelectedIndexChanging | Déclenche l'événement SelectedIndexChanging. | .gif) | OnSorted | Déclenche l'événement Sorted. | .gif) | OnSorting | Déclenche l'événement Sorting. | .gif) | OnTotalRowCountAvailable | Déclenche l'événement IPageableItemContainer..::.TotalRowCountAvailable. | .gif) | OnUnload | Déclenche l'événement Unload. (Hérité de Control.) | .gif) | OpenFile | Obtient un Stream utilisé pour lire un fichier. (Hérité de Control.) | .gif) | PerformDataBinding | Lie la source de données spécifiée au contrôle ListView. (Substitue DataBoundControl..::.PerformDataBinding(IEnumerable).) | .gif) | PerformSelect | Récupère les données de la source de données associée. (Substitue DataBoundControl..::.PerformSelect()()().) | .gif) | RaiseBubbleEvent | Assigne les sources éventuelles de l'événement et ses informations au parent du contrôle. (Hérité de Control.) | .gif) | RemovedControl | Appelée après la suppression d'un contrôle enfant dans la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | RemoveItems | Supprime tous les contrôles enfants dans un élément ou un conteneur de groupe du contrôle ListView. | .gif) | Render | Génère le rendu du contenu du contrôle serveur Web via le navigateur du client à l'aide de l'objet HtmlTextWriter spécifié. (Substitue WebControl..::.Render(HtmlTextWriter).) | .gif) | RenderBeginTag | Génère le rendu de la balise d'ouverture HTML du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | RenderChildren | Renvoie le contenu des enfants d'un contrôle serveur dans un objet HtmlTextWriter fourni, qui écrit le contenu à rendre sur le client. (Hérité de Control.) | .gif) | RenderContents | Génère le rendu du contenu du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | RenderControl(HtmlTextWriter) | Renvoie le contenu du contrôle serveur dans un objet HtmlTextWriter fourni et stocke des informations de traçage au sujet du contrôle si le traçage est activé. (Hérité de Control.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Génère le contenu du contrôle serveur dans un objet HtmlTextWriter à l'aide d'un objet ControlAdapter fourni. (Hérité de Control.) | .gif) | RenderEndTag | Génère le rendu de la balise de fermeture HTML du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | ResolveAdapter | Obtient l'adaptateur de contrôles responsable du rendu du contrôle spécifié. (Hérité de Control.) | .gif) | ResolveClientUrl | Obtient une URL qui peut être utilisée par le navigateur. (Hérité de Control.) | .gif) | ResolveUrl | Convertit une URL en une URL que le client soit en mesure d'utiliser. (Hérité de Control.) | .gif) | SaveControlState | Enregistre l'état des propriétés dans le contrôle ListView à faire persister, même lorsque la propriété EnableViewState a la valeur false. (Substitue Control..::.SaveControlState()()().) | .gif) | SaveViewState | Enregistre l'état d'affichage actuel du contrôle ListView. (Substitue WebControl..::.SaveViewState()()().) | .gif) | SelectItem | Sélectionne l'élément en mode édition dans un contrôle ListView. | .gif) | SetDesignModeState | Définit les données au moment du design pour un contrôle. (Hérité de Control.) | .gif) | SetEditItem | Définit l'élément spécifié en mode édition dans un contrôle ListView. | .gif) | SetPageProperties | Définit les propriétés d'une page de données dans le contrôle ListView. | .gif) | SetRenderMethodDelegate | Infrastructure. Assigne un délégué de gestionnaires d'événements pour générer le rendu du contrôle serveur et de son contenu dans son contrôle parent. (Hérité de Control.) | .gif) | Sort | Trie le contrôle ListView selon l'expression et le sens de tri spécifiés. | .gif) | ToString | Retourne une chaîne qui représente l'objet actuel. (Hérité de Object.) | .gif) | TrackViewState | Amène le contrôle à suivre les modifications apportées à son état d'affichage afin qu'elles puissent être stockées dans la propriété ViewState de l'objet. (Hérité de WebControl.) | .gif) | UpdateItem | Met à jour l'enregistrement à l'index spécifié dans la source de données. | .gif) | ValidateDataSource | Vérifie que l'objet auquel un contrôle lié aux données se lie est un objet avec qui il peut fonctionner. (Hérité de DataBoundControl.) | Début

Événements
|
| Nom | Description |
|---|
.gif) | DataBinding | Se produit lorsque le contrôle serveur se lie à une source de données. (Hérité de Control.) | .gif) | DataBound | Se produit après la liaison du contrôle serveur à une source de données. (Hérité de BaseDataBoundControl.) | .gif) | Disposed | Se produit lorsqu'un contrôle serveur est libéré de la mémoire, ce qui constitue la dernière étape du cycle de vie d'un contrôle serveur en cas de demande d'une page ASP.NET. (Hérité de Control.) | .gif) | Init | Se produit lorsque le contrôle serveur est initialisé, ce qui constitue la première étape de son cycle de vie. (Hérité de Control.) | .gif) | ItemCanceling | Se produit lorsqu'une opération d'annulation est demandée, mais avant que le contrôle ListView n'annule l'opération d'insertion ou de modification. | .gif) | ItemCommand | Se produit lorsque l'on clique sur un bouton dans un contrôle ListView. | .gif) | ItemCreated | Se produit lors de la création d'un élément dans un contrôle ListView. | .gif) | ItemDataBound | Se produit lorsqu'un élément de données est lié à des données dans un contrôle ListView. | .gif) | ItemDeleted | Se produit lorsqu'une opération de Suppression est demandée, après que le contrôle ListView ait supprimé l'élément. | .gif) | ItemDeleting | Se produit lorsqu'une opération de Suppression est demandée, mais avant que le contrôle ListView ait supprimé l'élément. | .gif) | ItemEditing | Se produit lorsqu'une modification est demandée, mais avant que l'élément ListView soit mis en mode Édition. | .gif) | ItemInserted | Se produit lorsqu'une opération d'insertion est demandée, après que le contrôle ListView a inséré l'élément dans la source de données. | .gif) | ItemInserting | Se produit lorsqu'une opération d'insertion est demandée, mais avant que le contrôle ListView n'exécute l'insertion. | .gif) | ItemUpdated | Se produit lorsqu'une opération de mise à jour est demandée, après que le contrôle ListView ait mis à jour l'élément. | .gif) | ItemUpdating | Se produit lorsqu'une opération de mise à jour est demandée, mais avant que le contrôle ListView n'ait mis à jour l'élément. | .gif) | LayoutCreated | Se produit lorsque le modèle LayoutTemplate est créé dans un contrôle ListView. | .gif) | Load | Se produit lorsque le contrôle serveur est chargé dans l'objet Page. (Hérité de Control.) | .gif) | PagePropertiesChanged | Se produit lorsque les propriétés de page sont modifiées, après que le contrôle ListView ait défini les nouvelles valeurs. | .gif) | PagePropertiesChanging | Se produit lorsque les propriétés de pages sont modifiées, mais avant que le contrôle ListView n'ai défini les nouvelles valeurs. | .gif) | PreRender | Se produit après le chargement de l'objet Control mais avant le rendu. (Hérité de Control.) | .gif) | SelectedIndexChanged | Se produit en cas de clic sur le bouton de sélection d'un élément, après que le contrôle ListView a géré l'opération de sélection. | .gif) | SelectedIndexChanging | Se produit en cas de clic sur le bouton de sélection d'un élément, mais avant que le contrôle ListView ne gère l'opération de sélection. | .gif) | Sorted | Se produit lorsqu'une opération de tri est demandée, après que le contrôle ListView ait géré l'opération de tri. | .gif) | Sorting | Se produit lorsqu'une opération de tri est demandée, mais avant que le contrôle ListView ne gère l'opération de tri. | .gif) | Unload | Se produit lorsque le contrôle serveur est déchargé de la mémoire. (Hérité de Control.) | Début

Méthodes d'extension

Implémentations d'interface explicite
|
| Nom | Description |
|---|
.gif) .gif) | IAttributeAccessor..::.GetAttribute | Infrastructure. Obtient un attribut du contrôle Web avec le nom spécifié. (Hérité de WebControl.) | .gif) .gif) | IAttributeAccessor..::.SetAttribute | Affecte au nom et à la valeur spécifiés un attribut du contrôle Web. (Hérité de WebControl.) | .gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | Pour obtenir une description de ce membre, consultez IControlBuilderAccessor..::.ControlBuilder. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.GetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetOwnerControl. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.UserData. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.DataBindings. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.HasDataBindings. (Hérité de Control.) | .gif) .gif) | IDataBoundControl..::.DataKeyNames | Obtient ou définit un tableau qui contient les noms des champs clé primaire des éléments qui sont affichés dans un contrôle lié aux données. | .gif) .gif) | IDataBoundControl..::.DataMember | Obtient ou définit le nom de la liste de données à laquelle le contrôle lié aux données se lie lorsque la source de données contient plusieurs listes distinctes d'éléments de données. | .gif) .gif) | IDataBoundControl..::.DataSource | Obtient ou définit l'objet duquel un contrôle lié aux données récupère sa liste d'éléments de données. | .gif) .gif) | IDataBoundControl..::.DataSourceID | Obtient ou définit l'ID du contrôle de source de données duquel un contrôle lié aux données récupère sa liste d'éléments de données. | .gif) .gif) | IDataBoundControl..::.DataSourceObject | Obtient un objet qui implémente l'interface IDataSource, qui fournit l'accès au contenu des données de l'objet. | .gif) .gif) | IDataBoundListControl..::.ClientIDRowSuffix | Obtient le nom du champ de données dont la valeur est utilisée pour identifier de façon unique chaque ligne de données d'un contrôle ListView lorsque la propriété ClientIDMode a la valeur Predictable. | .gif) .gif) | IDataBoundListControl..::.DataKeys | Obtient une collection de valeurs de clés de données qui représentent chaque ligne d'un contrôle lié aux données. | .gif) .gif) | IDataBoundListControl..::.EnablePersistedSelection | Obtient ou définit la valeur qui spécifie si une ligne sélectionnée persiste lorsqu'un utilisateur parcourt des données dans un contrôle lié aux données. | .gif) .gif) | IDataBoundListControl..::.SelectedDataKey | Obtient l'objet de clé de données qui contient la valeur de clé de données de la ligne sélectionnée dans un contrôle lié aux données. | .gif) .gif) | IDataBoundListControl..::.SelectedIndex | Obtient ou définit l'index de la ligne sélectionnée dans un contrôle lié aux données. | .gif) .gif) | IDataKeysControl..::.ClientIDRowSuffixDataKeys | Infrastructure. Obtient une collection de valeurs de données utilisées pour identifier de façon unique chaque instance d'un contrôle lié aux données lorsqu'ASP.NET génère la valeur ClientID. | .gif) .gif) | IExpressionsAccessor..::.Expressions | Pour obtenir une description de ce membre, consultez IExpressionsAccessor..::.Expressions. (Hérité de Control.) | .gif) .gif) | IExpressionsAccessor..::.HasExpressions | Pour obtenir une description de ce membre, consultez IExpressionsAccessor..::.HasExpressions. (Hérité de Control.) | .gif) .gif) | IPageableItemContainer..::.MaximumRows | Infrastructure. Pour obtenir une description de ce membre, consultez IPageableItemContainer..::.MaximumRows. | .gif) .gif) | IPageableItemContainer..::.SetPageProperties | Infrastructure. Pour obtenir une description de ce membre, consultez IPageableItemContainer..::.SetPageProperties. | .gif) .gif) | IPageableItemContainer..::.StartRowIndex | Infrastructure. Pour obtenir une description de ce membre, consultez IPageableItemContainer..::.StartRowIndex. | .gif) .gif) | IPageableItemContainer..::.TotalRowCountAvailable | Infrastructure. Pour obtenir une description de ce membre, consultez IPageableItemContainer..::.TotalRowCountAvailable. | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | Pour obtenir une description de ce membre, consultez IParserAccessor..::.AddParsedSubObject. (Hérité de Control.) | .gif) .gif) | IPersistedSelector..::.DataKey | Obtient ou définit la valeur de clé de données de l'enregistrement sélectionné dans un contrôle lié aux données. | Début

Notes
Dans cette rubrique : IntroductionLe contrôle ListView est utilisé pour afficher les valeurs à partir d'une source de données. Il ressemble au contrôle GridView, mais il affiche des données à l'aide de modèles définis par l'utilisateur au lieu de champs de ligne. La création de vos propres modèles offre davantage de souplesse pour contrôler la manière dont les données sont affichées. Un projet Visual Studio (avec code source) est disponible pour accompagner cette rubrique : Download. Le contrôle ListView prend en charge les fonctionnalités suivantes : Prise en charge de la liaison à des contrôles de sources de données, tels que SqlDataSource, LinqDataSource et ObjectDataSource. Apparence personnalisable grâce aux modèles et aux styles définis par l'utilisateur. Fonctionnalités intégrées de tri. Fonctionnalités intégrées de mise à jour et de suppression. Fonctionnalités d'insertion intégrées. Prise en charge de fonctionnalités de pagination à l'aide d'un contrôle DataPager. Fonctionnalités intégrées de sélection d'élément. Accès par programme au modèle objet ListView pour définir de manière dynamique la définition de propriétés, la gestion d'événements, etc. Plusieurs champs clés.
Pour en savoir plus sur les autres contrôles liés aux données disponibles dans ASP.NET, consultez Vue d'ensemble des contrôles serveur Web liés aux données ASP.NET. ModèlesPour que le contrôle ListView affiche le contenu, vous devez créer des modèles pour différentes parties du contrôle. La propriété ItemTemplate est requise. Tous les autres modèles sont facultatifs. La propriété LayoutTemplate n'est pas requise. Toutefois, vous devez créer un modèle pour le mode dans lequel le contrôle est configuré. Par exemple, un contrôle ListView qui prend en charge l'insertion d'enregistrements doit disposer d'un modèle InsertItemTemplate défini. Le tableau suivant énumère les modèles que vous pouvez créer pour le contrôle ListView. Type de modèle | Description |
|---|
LayoutTemplate
| Le modèle racine qui définit un objet de conteneur, tel qu'un élément table, div ou span, qui contiendra le contenu défini dans le modèle ItemTemplate ou GroupTemplate. Il peut contenir également un objet DataPager. |
ItemTemplate
| Définit le contenu lié aux données à afficher pour des éléments individuels. |
ItemSeparatorTemplate
| Définit le contenu à restituer entre des éléments individuels. |
GroupTemplate
| Définit un objet de conteneur, telle qu'une ligne de tableau tr, div ou un élément span, qui contiendra le contenu défini dans les modèles ItemTemplate et EmptyItemTemplate. Le nombre d'éléments qui sont affichés dans un groupe est spécifié par la propriété GroupItemCount. |
GroupSeparatorTemplate
| Définit le contenu à restituer entre des groupes d'éléments. |
EmptyItemTemplate
| Définit le contenu à restituer pour un élément vide lorsqu'un modèle GroupTemplate est utilisé. Par exemple, si la propriété GroupItemCount a la valeur 5, et que le nombre total d'éléments retourné par la source de données est 8, le dernier groupe de données affiché par le contrôle ListView contiendra trois éléments comme spécifié par le modèle ItemTemplate, et deux éléments comme spécifié par le modèle EmptyItemTemplate. |
EmptyDataTemplate
| Définit le contenu à restituer si la source de données ne retourne pas de données. |
SelectedItemTemplate
| Définit le contenu à restituer pour l'élément de données sélectionné pour différencier l'élément sélectionné d'autres éléments. |
AlternatingItemTemplate
| Définit le contenu à restituer pour les éléments de remplacement pour simplifier la distinction entre des éléments consécutifs. |
EditItemTemplate
| Définit le contenu à restituer lorsqu'un élément est modifié. Le modèle EditItemTemplate est restitué au lieu du modèle ItemTemplate pour l'élément de données modifié. |
InsertItemTemplate
| Définit le contenu à restituer pour insérer un élément. Le modèle InsertItemTemplate est restitué au lieu d'un modèle ItemTemplate au démarrage ou à la fin des éléments affichés par le contrôle ListView. Vous pouvez spécifier l'emplacement où le modèle InsertItemTemplate est rendu à l'aide de la propriété InsertItemPosition du contrôle ListView. |
Pour afficher la valeur d'un champ dans un modèle tel que ItemTemplate, utilisez une expression de liaison de données. Pour plus d'informations sur les expressions de liaison de données, consultez Vue d'ensemble des expressions de liaison de données. Pour lier des contrôles d'entrée dans les modèles EditItemTemplate et InsertItemTemplate aux champs d'une source de données, vous pouvez utiliser des expressions de liaison bidirectionnelles. Cela permet au contrôle ListView d'extraire automatiquement les valeurs du contrôle d'entrée pour une opération de mise à jour ou d'insertion. Les expressions de liaison bidirectionnelles permettent également aux contrôles d'entrée dans un EditItemTemplate d'afficher automatiquement les valeurs de champ d'origine. Pour plus d'informations sur les expressions de liaison bidirectionnelles, consultez Liaison à des bases de données. Liaison à une source de donnéesLe contrôle ListView peut être lié à un contrôle de source de données (tel que SqlDataSource ou ObjectDataSource) ou à toute source de données qui implémente l'interface System.Collections..::.IEnumerable, telle que System.Data..::.DataView, System.Collections..::.ArrayList, System.Collections.Generic..::.List<(Of <(T>)>) ou autres types de collection. Utilisez l'une des méthodes suivantes pour lier le contrôle ListView au type de source de données approprié : Pour lier à un contrôle de source de données, affectez à la propriété DataSourceID du contrôle ListView la valeur ID du contrôle de source de données. Le contrôle ListView se lie automatiquement au contrôle de source de données spécifié et peut tirer parti des fonctionnalités du contrôle de source de données pour exécuter des fonctionnalités de tri, d'insertion, de mise à jour, de suppression et de pagination. Il s'agit de la méthode recommandée de liaison aux données. Pour établir une liaison avec une source de données qui implémente l'interface System.Collections..::.IEnumerable, affectez par programme la propriété DataSource du contrôle ListView à la source de données, puis appelez la méthode DataBind. Lorsque vous utilisez cette technique, le contrôle ListView ne fournit pas de fonctionnalités intégrées de tri, de mise à jour, de suppression et de pagination. Vous devez fournir ces fonctionnalités en utilisant l'événement approprié.
Pour plus d'informations sur la liaison de données, consultez Accès aux données ASP.NET. Remarque |
|---|
Le contrôle ListView peut être utilisé pour afficher des entrées d'utilisateur qui peuvent inclure un script client malveillant. Recherchez dans toutes les informations envoyées par un client un script exécutable, des instructions SQL ou tout autre code avant de les afficher dans votre application. Dans la mesure du possible, il est fortement recommandé que les valeurs soient encodées en HTML avant de les afficher dans ce contrôle. ASP.NET fournit une fonctionnalité de validation de demande d'entrée pour aider à bloquer les scripts et le HTML dans les entrées d'utilisateur. Vous pouvez également utiliser des contrôles de serveur de validation pour vérifier l'entrée d'utilisateur. Pour plus d'informations, consultez Introduction to the Validation Controls. |
Opérations de donnéesLorsque le contrôle ListView est lié à un contrôle de source de données, le contrôle ListView peut tirer parti des fonctionnalités de contrôle de source de données et fournir des fonctionnalités automatiques de tri, d'insertion, de mise à jour et de suppression. Remarque |
|---|
Le contrôle ListView peut assurer la prise en charge requise pour trier, insérer, mettre à jour et supprimer avec d'autres types de sources de données. Toutefois, pour implémenter ces opérations, vous devez créer le code dans un gestionnaire d'événements approprié. |
Comme le contrôle ListView utilise des modèles, il n'offre pas de moyen de générer automatiquement des boutons pour exécuter les opérations de mise à jour, de suppression, d'insertion, de tri ou de sélection. Vous devez inclure manuellement ces boutons dans le modèle approprié. Le contrôle ListView reconnaît certains boutons dont la propriété CommandName a une valeur spécifique. Le tableau suivant répertorie les boutons que le contrôle ListView reconnaît et leurs fonctions. Contrairement au bouton Supprimer (lequel supprime immédiatement l'élément de données actuel), lorsque l'on clique sur le bouton Modifier, le contrôle ListView affiche l'élément actuel en mode Édition. En mode Édition, le contenu de la propriété EditItemTemplate est affiché pour l'élément de données actuel. En général, dans le modèle de modification d'élément, le bouton Modifier est remplacé par un bouton Mettre à jour et un bouton Annuler. Les contrôles d'entrée appropriés pour le type de données du champ (tels qu'un contrôle TextBox ou CheckBox) affichent aussi généralement la valeur d'un champ à modifier par l'utilisateur. Un clic sur le bouton Mettre à jour met à jour l'enregistrement dans la source de données et un clic sur le bouton Annuler annule l'opération d'édition. La fonctionnalité d'insertion est activée lorsque la propriété InsertItemPosition a la valeur FirstItem ou LastItem. Cette propriété définit où le modèle InsertItemTemplate est restitué pour l'élément d'insertion. Le modèle d'élément d'insertion inclut en général un bouton Insérer et un bouton Annuler, et les contrôles d'entrée vides sont affichés pour que les utilisateurs entrent les valeurs pour le nouvel enregistrement. Cliquer sur le bouton Insérer permet d'insérer l'enregistrement dans la source de données, et cliquer sur le bouton Annuler efface tous les champs. TriLe contrôle ListView permet aux utilisateurs de trier les éléments en cliquant sur le bouton Trier. La fonctionnalité de tri est définie dans la propriété CommandArgument du bouton qui contient les colonnes à trier. PaginationAu lieu d'afficher en même temps tous les enregistrements de la source de données, le contrôle ListView peut scinder les enregistrements en pages. Pour activer la pagination, associez un contrôle DataPager au contrôle ListView. Puis insérez un contrôle DataPager à l'intérieur du modèle LayoutTemplate. Ou bien, si le contrôle DataPager est à l'extérieur du contrôle ListView, affectez à la propriété PagedControlID la valeur ID du contrôle ListView. ÉvénementsLe tableau suivant répertorie les événements qui sont pris en charge par le contrôle ListView. Événement | Description |
|---|
ItemCanceling
| Se produit en cas de clic sur le bouton Annuler (bouton dont la propriété CommandName a la valeur "Cancel"), mais avant que le contrôle ListView n'annule l'opération d'insertion ou de modification. Cet événement est souvent utilisé pour arrêter l'opération d'annulation. |
ItemCommand
| Se produit lors d'un clic sur le bouton d'un contrôle ListView. Cet événement est souvent utilisé pour exécuter une tâche personnalisée lorsque l'on clique sur un bouton dans le contrôle. |
ItemCreated
| Se produit lorsqu'un nouvel élément est créé dans le contrôle ListView. Cet événement est souvent utilisé pour modifier le contenu d'un élément lors de sa création. |
ItemDataBound
| Se produit lorsqu'un élément de données est lié à des données dans le contrôle ListView. Cet événement est souvent utilisé pour modifier le contenu d'un élément lorsqu'il est lié à des données. |
ItemDeleted
| Se produit lorsque l'on clique sur un bouton Supprimer (bouton dont la propriété CommandName a la valeur "Delete") ou lorsque la méthode DeleteItem est appelée, après que le contrôle ListView ait supprimé l'enregistrement dans la source de données. Cet événement est souvent utilisé pour vérifier les résultats de l'opération de suppression. |
ItemDeleting
| Se produit lorsque l'on clique sur un bouton Supprimer (bouton dont la propriété CommandName a la valeur "Delete") ou lorsque la méthode DeleteItem est appelée, mais avant que le contrôle ListView n'ait supprimé l'enregistrement dans la source de données. Cet événement est souvent utilisé pour confirmer ou annuler l'opération de suppression. |
ItemEditing
| Se produit lorsque l'on clique sur un bouton Modifier (bouton dont la propriété CommandName a la valeur "Edit"), mais avant que le contrôle ListView passé en mode Édition. Cet événement est souvent utilisé pour annuler l'opération de modification. |
ItemInserted
| Se produit lorsque l'on clique sur un bouton Insérer (bouton dont la propriété CommandName a la valeur "Insert") ou lorsque la méthode InsertNewItem est appelée, après que le contrôle ListView ait inséré le nouvel enregistrement à partir de la source de données. Cet événement est souvent utilisé pour vérifier les résultats de l'opération d'insertion. |
ItemInserting
| Se produit lorsque l'on clique sur un bouton Insérer (bouton dont la propriété CommandName a la valeur "Insert") ou que l'on appelle la méthode InsertNewItem, mais avant que le contrôle ListView n'insère l'enregistrement. Cet événement est souvent utilisé pour annuler l'opération d'insertion ou pour modifier ou valider les valeurs du nouvel élément. |
ItemUpdated
| Se produit lorsque l'on clique sur le bouton Mettre à jour (bouton dont la propriété CommandName a la valeur "Update") ou lors de l'appel de la méthode UpdateItem, après que le contrôle ListView ait mis l'enregistrement à jour. Cet événement est souvent utilisé pour vérifier les résultats de l'opération de mise à jour. |
ItemUpdating
| Se produit lorsque l'on clique sur le bouton Mettre à jour (bouton dont la propriété CommandName a la valeur "Update") ou lors de l'appel de la méthode UpdateItem, mais avant que le contrôle ListView ait mis l'enregistrement à jour. Cet événement est souvent utilisé pour annuler l'opération de mise à jour ou pour modifier ou valider les valeurs de l'élément modifié. |
LayoutCreated
| Se produit lorsque le modèle LayoutTemplate est créé dans un contrôle ListView. Cet événement est souvent utilisé pour effectuer une tâche après création du modèle. |
PagePropertiesChanged
| Se produit lorsque les propriétés de page sont modifiées, après que le contrôle ListView ait défini les nouvelles valeurs. |
PagePropertiesChanging
| Se produit lorsque les propriétés de pages de données sont modifiées, mais avant que le contrôle ListView n'ai défini les nouvelles valeurs. |
SelectedIndexChanged
| Se produit lorsque l'on clique sur un bouton Sélectionner (bouton dont la propriété CommandName à la valeur "Select"), après que le contrôle ListView ait traité l'opération de sélection. Cet événement est souvent utilisé pour exécuter une tâche personnalisée après qu'un élément ait été sélectionné dans le contrôle. |
SelectedIndexChanging
| Se produit lorsque l'on clique sur un bouton Sélectionner (bouton dont la propriété CommandName à la valeur "Select"), mais avant que le contrôle ListView ait traité l'opération de sélection. Cet événement est souvent utilisé pour annuler l'opération de sélection. |
Sorted
| Se produit lorsque l'on clique sur un bouton Trier (bouton dont la propriété CommandName a la valeur "Sort") ou lors de l'appel de la méthode Sort, après que le contrôle ListView ait géré l'opération de tri. Cet événement est utilisé en général pour effectuer une tâche personnalisée après qu'un utilisateur ait cliqué sur un bouton Trier et que les données ont été triées. |
Sorting
| Se produit lorsque l'on clique sur un bouton Trier (bouton dont la propriété CommandName a la valeur "Sort") ou lors de l'appel de la méthode Sort, mais avant que le contrôle ListView ait géré l'opération de tri. Cet événement est souvent utilisé pour annuler l'opération de tri ou exécuter un programme de tri personnalisé. |
Syntaxe déclarative
<asp:ListView
ConvertEmptyStringToNull="True|False"
DataKeyNames="string"
DataMember="string"
DataSource="string"
DataSourceID="string"
EditIndex="integer"
Enabled="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
GroupPlaceholderID="string"
GroupItemCount="integer"
ID="string"
InsertItemPosition="None|FirstItem|LastItem"
ItemPlaceholderID="string"
OnDataBinding="DataBinding event handler"
OnDataBound="DataBound event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnItemCanceling="ItemCanceling event handler"
OnItemCommand="ItemCommand event handler"
OnItemCreated="ItemCreated event handler"
OnItemDataBound="ItemDataBound event handler"
OnItemDeleted="ItemDeleted event handler"
OnItemDeleting="ItemDeleting event handler"
OnItemEditing="ItemEditing event handler"
OnItemInserted="ItemInserted event handler"
OnItemInserting="ItemInserting event handler"
OnItemUpdated="ItemUpdated event handler"
OnItemUpdating="ItemUpdating event handler"
OnLayoutCreated="LayoutCreated event handler"
OnLoad="Load event handler"
OnPagePropertiesChanged="PagePropertiesChanged event handler"
OnPagePropertiesChanging="PagePropertiesChanging event handler"
OnPreRender="PreRender event handler"
OnSelectedIndexChanged="SelectedIndexChanged event handler"
OnSelectedIndexChanging="SelectedIndexChanging event handler"
OnSorted="Sorted event handler"
OnSorting="Sorting event handler"
OnUnload="Unload event handler"
runat="server"
SelectedIndex="integer"
SkinID="string"
Style="string"
Visible="True|False"
>
<AlternatingItemTemplate>
<!-- child controls -->
</AlternatingItemTemplate>
<EditItemTemplate>
<!-- child controls -->
</EditItemTemplate>
<EmptyDataTemplate>
<!-- child controls -->
</EmptyDataTemplate>
<EmptyItemTemplate>
<!-- child controls -->
</EmptyItemTemplate>
<GroupSeparatorTemplate>
<!-- child controls -->
</GroupSeparatorTemplate>
<GroupTemplate>
<!-- child controls -->
</GroupTemplate>
<InsertItemTemplate>
<!-- child controls -->
</InsertItemTemplate>
<ItemSeparatorTemplate>
<!-- child controls -->
</ItemSeparatorTemplate>
<ItemTemplate>
<!-- child controls -->
</ItemTemplate>
<LayoutTemplate>
<!-- child controls -->
</LayoutTemplate>
<SelectedItemTemplate>
<!-- child controls -->
</SelectedItemTemplate>
</asp:ListView>

Exemples
L'exemple suivant montre comment utiliser le contrôle ListView pour afficher des enregistrements d'une base de données en utilisant un tableau HTML. Les valeurs sont récupérées à l'aide d'un contrôle LinqDataSource.
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<asp:ListView ID="VendorsListView"
DataSourceID="VendorsDataSource"
DataKeyNames="VendorID"
runat="server">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" ID="tbl1" runat="server">
<tr runat="server" style="background-color: #98FB98">
<th runat="server">ID</th>
<th runat="server">Account Number</th>
<th runat="server">Name</th>
<th runat="server">Preferred Vendor</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("VendorID") %>' />
</td>
<td>
<asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("AccountNumber") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' /></td>
<td>
<asp:CheckBox ID="PreferredCheckBox" runat="server"
Checked='<%# Eval("PreferredVendorStatus") %>' Enabled="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Add a LINQ -->
<!-- to SQL class to the project to map to a table in -->
<!-- the database. -->
<asp:LinqDataSource ID="VendorsDataSource" runat="server"
ContextTypeName="AdventureWorksClassesDataContext"
Select="new (VendorID, AccountNumber, Name, PreferredVendorStatus)"
TableName="Vendors" Where="ActiveFlag == @ActiveFlag">
<WhereParameters>
<asp:Parameter DefaultValue="true" Name="ActiveFlag" Type="Boolean" />
</WhereParameters>
</asp:LinqDataSource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<asp:ListView ID="VendorsListView"
DataSourceID="VendorsDataSource"
DataKeyNames="VendorID"
runat="server">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" ID="tbl1" runat="server">
<tr runat="server" style="background-color: #98FB98">
<th runat="server">ID</th>
<th runat="server">Account Number</th>
<th runat="server">Name</th>
<th runat="server">Preferred Vendor</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("VendorID") %>' />
</td>
<td>
<asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("AccountNumber") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' /></td>
<td>
<asp:CheckBox ID="PreferredCheckBox" runat="server"
Checked='<%# Eval("PreferredVendorStatus") %>' Enabled="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Add a LINQ -->
<!-- to SQL class to the project to map to a table in -->
<!-- the database. -->
<asp:LinqDataSource ID="VendorsDataSource" runat="server"
ContextTypeName="AdventureWorksClassesDataContext"
Select="new (VendorID, AccountNumber, Name, PreferredVendorStatus)"
TableName="Vendors" Where="ActiveFlag == @ActiveFlag">
<WhereParameters>
<asp:Parameter DefaultValue="true" Name="ActiveFlag" Type="Boolean" />
</WhereParameters>
</asp:LinqDataSource>
</form>
</body>
</html>
L'exemple suivant montre comment utiliser le contrôle ListView pour afficher des valeurs dans une mise en page fluide à l'aide de l'élément div. Les valeurs sont récupérées à l'aide d'un contrôle SqlDataSource.
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Flow Layout Example</title>
<style type="text/css">
.plainBox {
font-family: Verdana, Arial, sans-serif;
font-size: 11px;
background: #ffffff;
border:1px solid #336666;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Flow Layout Example</h3>
Select the color:
<asp:DropDownList ID="ColorList" runat="server"
AutoPostBack="True"
DataSourceID="ColorDataSource"
DataTextField="Color"
DataValueField="Color">
</asp:DropDownList><br /><br />
<asp:ListView runat="server" ID="ProductListView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID">
<LayoutTemplate>
<div runat="server" id="lstProducts">
<div runat="server" id="itemPlaceholder" />
</div>
<asp:DataPager ID="DataPager1" runat="server" PageSize="5" >
<Fields>
<asp:NextPreviousPagerField
ButtonType="Button"
ShowFirstPageButton="True"
ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<asp:Image ID="ProductImage" runat="server"
ImageUrl='<%# "~/images/thumbnails/" & Eval("ThumbnailPhotoFileName") %>' />
<div class="plainBox" runat="server">
<asp:HyperLink ID="ProductLink" runat="server" Text='<%# Eval("Name") %>'
NavigateUrl='<%# "ProductDetails.aspx?productID=" & Eval("ProductID") %>' />
<br /><br />
<b>Price:</b>
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("ListPrice", "{0:c}")%>' /> <br />
</div>
<br />
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource ID="ProductsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT P.ProductID, P.Name, P.Color, P.ListPrice,
PF.ThumbnailPhotoFileName, P.Size
FROM Production.Product AS P
INNER JOIN Production.ProductProductPhoto AS PPF ON P.ProductID = PPF.ProductID
INNER JOIN Production.ProductPhoto AS PF ON PPF.ProductPhotoID = PF.ProductPhotoID
WHERE P.Color = @Color" >
<SelectParameters>
<asp:ControlParameter ControlID="ColorList" Name="Color"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="ColorDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT DISTINCT Color FROM Production.Product">
</asp:SqlDataSource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Flow Layout Example</title>
<style type="text/css">
.plainBox {
font-family: Verdana, Arial, sans-serif;
font-size: 11px;
background: #ffffff;
border:1px solid #336666;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Flow Layout Example</h3>
Select the color:
<asp:DropDownList ID="ColorList" runat="server"
AutoPostBack="True"
DataSourceID="ColorDataSource"
DataTextField="Color"
DataValueField="Color">
</asp:DropDownList><br /><br />
<asp:ListView runat="server" ID="ProductListView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID">
<LayoutTemplate>
<div runat="server" id="lstProducts">
<div runat="server" id="itemPlaceholder" />
</div>
<asp:DataPager runat="server" PageSize="5" >
<Fields>
<asp:NextPreviousPagerField
ButtonType="Button"
ShowFirstPageButton="True"
ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<asp:Image ID="ProductImage" runat="server"
ImageUrl='<%# "~/images/thumbnails/" + Eval("ThumbnailPhotoFileName") %>' />
<div class="plainBox" runat="server">
<asp:HyperLink ID="ProductLink" runat="server" Text='<%# Eval("Name") %>'
NavigateUrl='<%# "ProductDetails.aspx?productID=" + Eval("ProductID") %>' />
<br /><br />
<b>Price:</b>
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("ListPrice", "{0:c}")%>' /> <br />
</div>
<br />
</ItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource ID="ProductsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT P.ProductID, P.Name, P.Color, P.ListPrice,
PF.ThumbnailPhotoFileName, P.Size
FROM Production.Product AS P
INNER JOIN Production.ProductProductPhoto AS PPF ON P.ProductID = PPF.ProductID
INNER JOIN Production.ProductPhoto AS PF ON PPF.ProductPhotoID = PF.ProductPhotoID
WHERE P.Color = @Color" >
<SelectParameters>
<asp:ControlParameter ControlID="ColorList" Name="Color"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="ColorDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT DISTINCT Color FROM Production.Product">
</asp:SqlDataSource>
</form>
</body>
</html>
L'exemple suivant montre comment utiliser le contrôle ListView pour insérer, supprimer et mettre des enregistrements à jour. Note de sécurité |
|---|
Cet exemple a une zone de texte qui accepte l'entrée d'utilisateur, ce qui constitue une menace éventuelle pour la sécurité. Par défaut, les pages Web ASP.NET vérifient que l'entrée d'utilisateur n'inclut pas de script ni d'éléments HTML. Pour plus d'informations, consultez Vue d'ensemble des attaques de script. |
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Example</title>
<style type="text/css">
.EditItem { background-color:#8FBC8F;}
.SelectedItem { background-color:#9ACD32; }
.InsertItem { background-color:#FFFACD;}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<h5>Departments</h5>
<asp:ListView ID="DepartmentsListView"
DataSourceID="DepartmentsDataSource"
DataKeyNames="DepartmentID"
ConvertEmptyStringToNull="true"
InsertItemPosition="LastItem"
runat="server">
<LayoutTemplate>
<table cellpadding="2" runat="server" id="tblDepartments" width="640px" cellspacing="0">
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select" />
<asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
</td>
<td>
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
</td>
<td>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr class="SelectedItem" runat="server">
<td>
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" />
<asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
</td>
<td>
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
</td>
<td>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
</td>
</tr>
</SelectedItemTemplate>
<EditItemTemplate>
<tr class="EditItem">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<b>ID</b><br />
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox"
Text="Name" Font-Bold="true"/><br />
<asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' />
</td>
<td>
<asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox"
Text="Group Name" Font-Bold="true" /><br />
<asp:TextBox ID="GroupNameTextBox" runat="server"
Width="200px"
Text='<%#Bind("GroupName") %>' />
<br />
</td>
</tr>
</EditItemTemplate>
<InsertItemTemplate>
<tr class="InsertItem">
<td colspan="2">
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox"
Text="Name" Font-Bold="true"/><br />
<asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' /><br />
</td>
<td>
<asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox"
Text="Group Name" Font-Bold="true" /><br />
<asp:TextBox ID="GroupNameTextBox" runat="server" Text='<%#Bind("GroupName") %>' />
</td>
</tr>
</InsertItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource ID="DepartmentsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department"
UpdateCommand="UPDATE HumanResources.Department
SET Name = @Name, GroupName = @GroupName WHERE (DepartmentID = @DepartmentID)"
DeleteCommand="DELETE FROM HumanResources.Department
WHERE (DepartmentID = @DepartmentID)"
InsertCommand="INSERT INTO HumanResources.Department(Name, GroupName)
VALUES (@Name, @GroupName)">
</asp:SqlDataSource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head id="Head1" runat="server">
<title>ListView Example</title>
<style type="text/css">
.EditItem { background-color:#8FBC8F;}
.SelectedItem { background-color:#9ACD32; }
.InsertItem { background-color:#FFFACD;}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<h5>Departments</h5>
<asp:ListView ID="DepartmentsListView"
DataSourceID="DepartmentsDataSource"
DataKeyNames="DepartmentID"
ConvertEmptyStringToNull="true"
InsertItemPosition="LastItem"
runat="server">
<LayoutTemplate>
<table cellpadding="2" runat="server" id="tblDepartments" width="640px" cellspacing="0">
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select" />
<asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
</td>
<td>
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
</td>
<td>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr class="SelectedItem" runat="server">
<td>
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" />
<asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
</td>
<td>
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
</td>
<td>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
</td>
</tr>
</SelectedItemTemplate>
<EditItemTemplate>
<tr class="EditItem">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<b>ID</b><br />
<asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
</td>
<td>
<asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox"
Text="Name" Font-Bold="true"/><br />
<asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' />
</td>
<td>
<asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox"
Text="Group Name" Font-Bold="true" /><br />
<asp:TextBox ID="GroupNameTextBox" runat="server"
Width="200px"
Text='<%#Bind("GroupName") %>' />
<br />
</td>
</tr>
</EditItemTemplate>
<InsertItemTemplate>
<tr class="InsertItem">
<td colspan="2">
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox"
Text="Name" Font-Bold="true"/><br />
<asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' /><br />
</td>
<td>
<asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox"
Text="Group Name" Font-Bold="true" /><br />
<asp:TextBox ID="GroupNameTextBox" runat="server" Text='<%#Bind("GroupName") %>' />
</td>
</tr>
</InsertItemTemplate>
</asp:ListView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource ID="DepartmentsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department"
UpdateCommand="UPDATE HumanResources.Department
SET Name = @Name, GroupName = @GroupName WHERE (DepartmentID = @DepartmentID)"
DeleteCommand="DELETE FROM HumanResources.Department
WHERE (DepartmentID = @DepartmentID)"
InsertCommand="INSERT INTO HumanResources.Department(Name, GroupName)
VALUES (@Name, @GroupName)">
</asp:SqlDataSource>
</form>
</body>
</html>

Informations de version
.NET FrameworkPris en charge dans : 4, 3.5

Plateformes
Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2
Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.

Sécurité des threads
Tous les membres static ( Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Voir aussi
RéférenceAutres ressources
|