.NET Framework Class Library GridView Class Updated: July 2008 Displays the values of a data source in a table where each column represents a field and each row represents a record. The GridView control enables you to select, sort, and edit these items.

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

Syntax
<ControlValuePropertyAttribute("SelectedValue")> _
Public Class GridView _
Inherits CompositeDataBoundControl _
Implements IPostBackContainer, IPostBackEventHandler, ICallbackContainer, ICallbackEventHandler, _
IPersistedSelector, IDataKeysControl, IDataBoundListControl, IDataBoundControl, IFieldControl
[ControlValuePropertyAttribute("SelectedValue")]
public class GridView : CompositeDataBoundControl, IPostBackContainer,
IPostBackEventHandler, ICallbackContainer, ICallbackEventHandler, IPersistedSelector, IDataKeysControl,
IDataBoundListControl, IDataBoundControl, IFieldControl
[ControlValuePropertyAttribute(L"SelectedValue")]
public ref class GridView : public CompositeDataBoundControl,
IPostBackContainer, IPostBackEventHandler, ICallbackContainer, ICallbackEventHandler, IPersistedSelector,
IDataKeysControl, IDataBoundListControl, IDataBoundControl, IFieldControl
[<ControlValuePropertyAttribute("SelectedValue")>]
type GridView =
class
inherit CompositeDataBoundControl
interface IPostBackContainer
interface IPostBackEventHandler
interface ICallbackContainer
interface ICallbackEventHandler
interface IPersistedSelector
interface IDataKeysControl
interface IDataBoundListControl
interface IDataBoundControl
interface IFieldControl
end
The GridView type exposes the following members.

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

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) | 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) | CreateAutoGeneratedColumn | Creates an automatically generated column field. | .gif) | CreateChildControls()()() | Infrastructure. Creates the control hierarchy that is used to render a composite data-bound control based on the values that are stored in view state. (Inherited from CompositeDataBoundControl.) | .gif) | CreateChildControls(IEnumerable, Boolean) | Infrastructure. Creates the control hierarchy used to render the GridView control using the specified data source. (Overrides CompositeDataBoundControl..::.CreateChildControls(IEnumerable, Boolean).) | .gif) | CreateChildTable | Infrastructure. Creates a new child table. | .gif) | CreateColumns | Creates the set of column fields used to build the control hierarchy. | .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 | Infrastructure. Creates the default style for the control. (Overrides WebControl..::.CreateControlStyle()()().) | .gif) | CreateDataSourceSelectArguments | Creates the DataSourceSelectArguments object that contains the arguments that get passed to the data source for processing. (Overrides DataBoundControl..::.CreateDataSourceSelectArguments()()().) | .gif) | CreateRow | Creates a row in the GridView control. | .gif) | DataBind()()() | Binds the data source to the GridView control. This method cannot be inherited. (Overrides BaseDataBoundControl..::.DataBind()()().) | .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) | DeleteRow | 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) | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | .gif) | ExtractRowValues | Retrieves the values of each field declared within the specified row 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) | Focus | Sets input focus to a control. (Inherited from Control.) | .gif) | GetCallbackResult | Returns the result of a callback event that targets a control. | .gif) | GetCallbackScript | Creates the callback script for a button that performs a sorting operation. | .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) | InitializePager | Initializes the pager row displayed when the paging feature is enabled. | .gif) | InitializeRow | Initializes a row in the GridView control. | .gif) | IsBindableType | Determines whether the specified data type can be bound to a column in a GridView control. | .gif) | IsLiteralContent | Infrastructure. Determines if the server control holds only literal content. (Inherited from Control.) | .gif) | LoadControlState | Infrastructure. Loads the state of the properties in the GridView control that need to be persisted, even when the Control..::.EnableViewState property is set to false. (Overrides Control..::.LoadControlState(Object).) | .gif) | LoadViewState | Loads the previously saved view state of the GridView 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 the event for the Web server control is passed up the page's user interface (UI) server control hierarchy. (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 GridView control to its data after the DataMember, DataSource, or DataSourceID property is changed. (Overrides DataBoundControl..::.OnDataPropertyChanged()()().) | .gif) | OnDataSourceViewChanged | Raises the DataSourceViewChanged event. (Overrides DataBoundControl..::.OnDataSourceViewChanged(Object, EventArgs).) | .gif) | OnInit | Raises the Control..::.Init event. (Overrides BaseDataBoundControl..::.OnInit(EventArgs).) | .gif) | OnLoad | Handles the Control..::.Load event. (Inherited from DataBoundControl.) | .gif) | OnPageIndexChanged | Raises the PageIndexChanged event. | .gif) | OnPageIndexChanging | Raises the PageIndexChanging event. | .gif) | OnPagePreLoad | Sets the initialized state of the data-bound control before the control is loaded. (Overrides DataBoundControl..::.OnPagePreLoad(Object, EventArgs).) | .gif) | OnPreRender | Infrastructure. Raises the PreRender event. (Overrides BaseDataBoundControl..::.OnPreRender(EventArgs).) | .gif) | OnRowCancelingEdit | Raises the RowCancelingEdit event. | .gif) | OnRowCommand | Raises the RowCommand event. | .gif) | OnRowCreated | Raises the RowCreated event. | .gif) | OnRowDataBound | Raises the RowDataBound event. | .gif) | OnRowDeleted | Raises the RowDeleted event. | .gif) | OnRowDeleting | Raises the RowDeleting event. | .gif) | OnRowEditing | Raises the RowEditing event. | .gif) | OnRowUpdated | Raises the RowUpdated event. | .gif) | OnRowUpdating | Raises the RowUpdating event. | .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) | OnUnload | Raises the Unload event. (Inherited from Control.) | .gif) | OpenFile | Gets a Stream used to read a file. (Inherited from Control.) | .gif) | PerformDataBinding | Infrastructure. Binds the specified data source to the GridView control. (Overrides CompositeDataBoundControl..::.PerformDataBinding(IEnumerable).) | .gif) | PerformSelect | Retrieves data from the associated data source. (Inherited from DataBoundControl.) | .gif) | PrepareControlHierarchy | Infrastructure. Establishes the control hierarchy. | .gif) | RaiseBubbleEvent | Assigns any sources of the event and its information to the control's parent. (Inherited from Control.) | .gif) | RaiseCallbackEvent | Creates the arguments for the callback handler in the GetCallbackEventReference method. | .gif) | RaisePostBackEvent | Raises the appropriate events for the GridView control when it posts back to the server. | .gif) | RemovedControl | Called after a child control is removed from the Controls collection of the Control object. (Inherited from Control.) | .gif) | Render | Infrastructure. Renders the Web server control content to the client's browser using the specified System.Web.UI..::.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 | Infrastructure. Saves the state of the properties in the GridView control that need to be persisted, even when the Control..::.EnableViewState property is set to false. (Overrides Control..::.SaveControlState()()().) | .gif) | SaveViewState | Infrastructure. Loads the previously saved view state of the GridView control. (Overrides WebControl..::.SaveViewState()()().) | .gif) | SelectRow | Selects the row to edit in a GridView control. | .gif) | SetDesignModeState | Sets design-time data for a control. (Inherited from Control.) | .gif) | SetEditRow | Puts a row in edit mode in a GridView control by using the specified row index. | .gif) | SetPageIndex | Sets the page index of the GridView control by using the row index. | .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 GridView control based on the specified sort expression and direction. | .gif) | ToString | Returns a string that represents the current object. (Inherited from Object.) | .gif) | TrackViewState | Infrastructure. Tracks view-state changes to the GridView control so they can be stored in the control's System.Web.UI..::.StateBag object. This object is accessible through the Control..::.ViewState property. (Overrides WebControl..::.TrackViewState()()().) | .gif) | UpdateRow | Updates the record at the specified row index using the field values of the row. | .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) | Load | Occurs when the server control is loaded into the Page object. (Inherited from Control.) | .gif) | PageIndexChanged | Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. | .gif) | PageIndexChanging | Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. | .gif) | PreRender | Occurs after the Control object is loaded but prior to rendering. (Inherited from Control.) | .gif) | RowCancelingEdit | Occurs when the Cancel button of a row in edit mode is clicked, but before the row exits edit mode. | .gif) | RowCommand | Occurs when a button is clicked in a GridView control. | .gif) | RowCreated | Occurs when a row is created in a GridView control. | .gif) | RowDataBound | Occurs when a data row is bound to data in a GridView control. | .gif) | RowDeleted | Occurs when a row's Delete button is clicked, but after the GridView control deletes the row. | .gif) | RowDeleting | Occurs when a row's Delete button is clicked, but before the GridView control deletes the row. | .gif) | RowEditing | Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode. | .gif) | RowUpdated | Occurs when a row's Update button is clicked, but after the GridView control updates the row. | .gif) | RowUpdating | Occurs when a row's Update button is clicked, but before the GridView control updates the row. | .gif) | SelectedIndexChanged | Occurs when a row's Select button is clicked, but after the GridView control handles the select operation. | .gif) | SelectedIndexChanging | Occurs when a row's Select button is clicked, but before the GridView control handles the select operation. | .gif) | Sorted | Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. | .gif) | Sorting | Occurs when the hyperlink to sort a column is clicked, but before the GridView 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) | ICallbackContainer..::.GetCallbackScript | Infrastructure. Creates the callback script for a button that performs a sorting operation. | .gif) .gif) | ICallbackEventHandler..::.GetCallbackResult | Infrastructure. Returns the result of a callback event that targets a control. | .gif) .gif) | ICallbackEventHandler..::.RaiseCallbackEvent | Infrastructure. Creates the arguments for the callback handler in the GetCallbackEventReference method. | .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 the names of the primary key fields for the items displayed in a data-bound control. | .gif) .gif) | IDataBoundControl..::.DataMember | Gets or sets the table that is exposed by the data source control to bind to the data-bound control. | .gif) .gif) | IDataBoundControl..::.DataSource | Gets or sets the data source object from which the data-bound control retrieves the list of data items. | .gif) .gif) | IDataBoundControl..::.DataSourceID | Gets or sets the ID of the data source from which the data-bound control retrieves the list of data items. | .gif) .gif) | IDataBoundControl..::.DataSourceObject | Gets or sets the data source object from which the data-bound control retrieves the list of data items. | .gif) .gif) | IDataBoundListControl..::.ClientIDRowSuffix | Gets or sets the names of the data fields whose values are appended to the ClientID property value to uniquely identify each instance of a data-bound control. | .gif) .gif) | IDataBoundListControl..::.DataKeys | Gets a collection of objects that represent the DataKeys value in a data-bound control. | .gif) .gif) | IDataBoundListControl..::.EnablePersistedSelection | Gets or sets a value that indicates whether the selection of a row is based on index or on data-key values. | .gif) .gif) | IDataBoundListControl..::.SelectedDataKey | Gets the 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 the data-bound control. | .gif) .gif) | IDataKeysControl..::.ClientIDRowSuffixDataKeys | Infrastructure. Gets 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) | IFieldControl..::.FieldsGenerator | Gets or sets the control that automatically generates the columns for a data-bound control for use by ASP.NET Dynamic Data. | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | For a description of this member, see IParserAccessor..::.AddParsedSubObject. (Inherited from Control.) | .gif) .gif) | IPersistedSelector..::.DataKey | For a description of this member, see IPersistedSelector..::.DataKey. | .gif) .gif) | IPostBackContainer..::.GetPostBackOptions | Infrastructure. Creates a PostBackOptions object that represents the postback behavior of the specified button control. | .gif) .gif) | IPostBackEventHandler..::.RaisePostBackEvent | Infrastructure. Raises the appropriate events for the GridView control when it posts back to the server. | Top

Remarks
In this topic: IntroductionThe GridView control is used to display the values of a data source in a table. Each column represents a field, while each row represents a record. The GridView control supports the following features: Binding to data source controls, such as SqlDataSource. Built-in sort capabilities. Built-in update and delete capabilities. Built-in paging capabilities. Built-in row selection capabilities. Programmatic access to the GridView object model to dynamically set properties, handle events, and so on. Multiple key fields. Multiple data fields for the hyperlink columns. Customizable appearance through themes and styles. To learn about the other data-bound controls that are available in ASP.NET, see ASP.NET Data-Bound Web Server Controls Overview.
Note |
|---|
If you are familiar with the DataGrid control from the .NET Framework version 1.0, the GridView control is the successor to the DataGrid control. |
Column FieldsEach column in the GridView control is represented by a DataControlField object. By default, the AutoGenerateColumns property is set to true, which creates an AutoGeneratedField object for each field in the data source. Each field is then rendered as a column in the GridView control in the order that each field appears in the data source. You can also manually control which column fields appear in the GridView control by setting the AutoGenerateColumns property to false and then defining your own column field collection. Different column field types determine the behavior of the columns in the control. The following table lists the different column field types that can be used. Column field type | Description |
|---|
BoundField
| Displays the value of a field in a data source. This is the default column type of the GridView control. |
ButtonField
| Displays a command button for each item in the GridView control. This enables you to create a column of custom button controls, such as the Add or the Remove button. |
CheckBoxField
| Displays a check box for each item in the GridView control. This column field type is commonly used to display fields with a Boolean value. |
CommandField
| Displays predefined command buttons to perform select, edit, or delete operations. |
HyperLinkField
| Displays the value of a field in a data source as a hyperlink. This column field type enables you to bind a second field to the hyperlink's URL. |
ImageField
| Displays an image for each item in the GridView control. |
TemplateField
| Displays user-defined content for each item in the GridView control according to a specified template. This column field type enables you to create a custom column field. |
To define a column field collection declaratively, first add opening and closing <Columns> tags between the opening and closing tags of the GridView control. Next, list the column fields that you want to include between the opening and closing <Columns> tags. The columns specified are added to the Columns collection in the order listed. The Columns collection stores all the column fields in the control and enables you to programmatically manage the column fields in the GridView control. Explicitly declared column fields can be displayed in combination with automatically generated column fields. When both are used, explicitly declared column fields are rendered first, followed by the automatically generated column fields. Note |
|---|
Automatically generated column fields are not added to the Columns collection. |
Binding to DataThe GridView control can be bound 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 GridView control to the appropriate data source type: To bind to a data source control, set the DataSourceID property of the GridView control to the ID value of the data source control. The GridView control automatically binds to the specified data source control and can take advantage of the data source control's capabilities to perform sorting, updating, deleting, and paging. 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 GridView control to the data source and then call the DataBind method. When using this method, the GridView control does not provide built-in sort, update, delete, and paging functionality. You need to provide this functionality by using the appropriate event.
For more information about data binding, see ASP.NET Data Access. Note |
|---|
This control can be used to display user input, which might include malicious client script. Check any information that is sent from a client for executable script, SQL statements, or other code before displaying it in your application. Whenever possible, it is strongly recommended that values are HTML-encoded before they are displayed in this control (the BoundField class HTML-encodes values by default). ASP.NET provides an input request validation feature to block script and HTML in user input. Validation server controls are also provided to assess user input. For more information, see Introduction to the Validation Controls. |
Data OperationsThe GridView control provides many built-in capabilities that allow the user to sort, update, delete, select, and page through items in the control. When the GridView control is bound to a data source control, the GridView control can take advantage of the data source control's capabilities and provide automatic sort, update, and delete functionality. Note |
|---|
The GridView control can provide support for sorting, updating, and deleting with other types of data sources. However, you will need to provide an appropriate event handler with the implementation for these operations. |
Sorting allows the user to sort the items in the GridView control with respect to a specific column by clicking on the column's header. To enable sorting, set the AllowSorting property to true. The automatic updating, deleting, and selection functionalities are enabled when a button in a ButtonField or TemplateField column field, with a command name of "Edit", "Delete", and "Select", respectively, is clicked. The GridView control can automatically add a CommandField column field with an Edit, Delete, or Select button if the AutoGenerateEditButton, AutoGenerateDeleteButton, or AutoGenerateSelectButton property is set to true, respectively. Note |
|---|
Inserting records into the data source is not directly supported by the GridView control. However, it is possible to insert records by using the GridView control in conjunction with the DetailsView or FormView control. For more information, see DetailsView or FormView, respectively. |
Instead of displaying all the records in the data source at the same time, the GridView control can automatically break the records up into pages. To enable paging, set the AllowPaging property to true. Note |
|---|
The GridView control is re-created on postback based on the information that is stored in ViewState. If the GridView control includes a TemplateField or a CommandField with the CausesValidation property set to true, then the EnableViewState property must also be set to true to ensure that concurrent data operations, such as updates and deletes, apply to the appropriate row. |
Customizing the User InterfaceYou can customize the appearance of the GridView control by setting the style properties for the different parts of the control. The following table lists the different style properties. Style property | Description |
|---|
AlternatingRowStyle
| The style settings for the alternating data rows in the GridView control. When this property is set, the data rows are displayed alternating between the RowStyle settings and the AlternatingRowStyle settings. |
EditRowStyle
| The style settings for the row being edited in the GridView control. |
EmptyDataRowStyle
| The style settings for the empty data row displayed in the GridView control when the data source does not contain any records. |
FooterStyle
| The style settings for the footer row of the GridView control. |
HeaderStyle
| The style settings for the header row of the GridView control. |
PagerStyle
| The style settings for the pager row of the GridView control. |
RowStyle
| The style settings for the data rows in the GridView control. When the AlternatingRowStyle property is also set, the data rows are displayed alternating between the RowStyle settings and the AlternatingRowStyle settings. |
SelectedRowStyle
| The style settings for the selected row in the GridView control. |
SortedAscendingCellStyle
| The style setting for the data column the data is sorted by in the GridView control. When this style is set, the style (for example, highlighted column) is applied to cells when the data is sorted in ascending order. |
SortedAscendingHeaderStyle
| The style setting for the data column the data is sorted by in the GridView control. When this style is set, an arrow indicating the data is sorted ascending is placed on the header of the GridView control when the data is sorted in ascending order. |
SortedDescendingCellStyle
| The style setting for the data column the data is sorted by in the GridView control. When this style is set, the style (for example, highlighted column) is applied to cells when the data is sorted in descending order. |
SortedDescendingHeaderStyle
| The style setting for the data column the data is sorted by in the GridView control. When this style is set, an arrow pointing down is placed on the header of the GridView when the data is sorted in descending order. |
You can also show or hide different parts of the control. The following table lists the properties that control which parts are shown or hidden. Property | Description |
|---|
ShowFooter
| Shows or hides the footer section of the GridView control. |
ShowHeader
| Shows or hides the header section of the GridView control. |
EventsThe GridView control provides several events that you can program against. This enables you to run a custom routine whenever an event occurs. The following table lists the events that are supported by the GridView control. Event | Description |
|---|
PageIndexChanged
| Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. This event is commonly used when you need to perform a task after the user navigates to a different page in the control. |
PageIndexChanging
| Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. This event is often used to cancel the paging operation. |
RowCancelingEdit
| Occurs when a row's Cancel button is clicked, but before the GridView control exits edit mode. This event is often used to stop the canceling operation. |
RowCommand
| Occurs when a button is clicked in the GridView control. This event is often used to perform a task when a button is clicked in the control. |
RowCreated
| Occurs when a new row is created in the GridView control. This event is often used to modify the contents of a row when the row is created. |
RowDataBound
| Occurs when a data row is bound to data in the GridView control. This event is often used to modify the contents of a row when the row is bound to data. |
RowDeleted
| Occurs when a row's Delete button is clicked, but after the GridView control deletes the record from the data source. This event is often used to check the results of the delete operation. |
RowDeleting
| Occurs when a row's Delete button is clicked, but before the GridView control deletes the record from the data source. This event is often used to cancel the deleting operation. |
RowEditing
| Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode. This event is often used to cancel the editing operation. |
RowUpdated
| Occurs when a row's Update button is clicked, but after the GridView control updates the row. This event is often used to check the results of the update operation. |
RowUpdating
| Occurs when a row's Update button is clicked, but before the GridView control updates the row. This event is often used to cancel the updating operation. |
SelectedIndexChanged
| Occurs when a row's Select button is clicked, but after the GridView control handles the select operation. This event is often used to perform a task after a row is selected in the control. |
SelectedIndexChanging
| Occurs when a row's Select button is clicked, but before the GridView control handles the select operation. This event is often used to cancel the selection operation. |
Sorted
| Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. This event is commonly used to perform a task after the user clicks a hyperlink to sort a column. |
Sorting
| Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation. This event is often used to cancel the sorting operation or to perform a custom sorting routine. |
AccessibilityDeclarative Syntax
<asp:GridView
AccessKey="string"
AllowPaging="True|False"
AllowSorting="True|False"
AutoGenerateColumns="True|False"
AutoGenerateDeleteButton="True|False"
AutoGenerateEditButton="True|False"
AutoGenerateSelectButton="True|False"
BackColor="color name|#dddddd"
BackImageUrl="uri"
BorderColor="color name|#dddddd"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset"
BorderWidth="size"
Caption="string"
CaptionAlign="NotSet|Top|Bottom|Left|Right"
CellPadding="integer"
CellSpacing="integer"
CssClass="string"
DataKeyNames="string"
DataMember="string"
DataSource="string"
DataSourceID="string"
EditIndex="integer"
EmptyDataText="string"
Enabled="True|False"
EnableSortingAndPagingCallbacks="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
GridLines="None|Horizontal|Vertical|Both"
Height="size"
HorizontalAlign="NotSet|Left|Center|Right|Justify"
ID="string"
OnDataBinding="DataBinding event handler"
OnDataBound="DataBound event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnLoad="Load event handler"
OnPageIndexChanged="PageIndexChanged event handler"
OnPageIndexChanging="PageIndexChanging event handler"
OnPreRender="PreRender event handler"
OnRowCancelingEdit="RowCancelingEdit event handler"
OnRowCommand="RowCommand event handler"
OnRowCreated="RowCreated event handler"
OnRowDataBound="RowDataBound event handler"
OnRowDeleted="RowDeleted event handler"
OnRowDeleting="RowDeleting event handler"
OnRowEditing="RowEditing event handler"
OnRowUpdated="RowUpdated event handler"
OnRowUpdating="RowUpdating event handler"
OnSelectedIndexChanged="SelectedIndexChanged event handler"
OnSelectedIndexChanging="SelectedIndexChanging event handler"
OnSorted="Sorted event handler"
OnSorting="Sorting event handler"
OnUnload="Unload event handler"
PageIndex="integer"
PagerSettings-FirstPageImageUrl="uri"
PagerSettings-FirstPageText="string"
PagerSettings-LastPageImageUrl="uri"
PagerSettings-LastPageText="string"
PagerSettings-Mode="NextPrevious|Numeric|NextPreviousFirstLast|
NumericFirstLast"
PagerSettings-NextPageImageUrl="uri"
PagerSettings-NextPageText="string"
PagerSettings-PageButtonCount="integer"
PagerSettings-Position="Bottom|Top|TopAndBottom"
PagerSettings-PreviousPageImageUrl="uri"
PagerSettings-PreviousPageText="string"
PagerSettings-Visible="True|False"
PageSize="integer"
RowHeaderColumn="string"
runat="server"
SelectedIndex="integer"
ShowFooter="True|False"
ShowHeader="True|False"
SkinID="string"
Style="string"
TabIndex="integer"
ToolTip="string"
UseAccessibleHeader="True|False"
Visible="True|False"
Width="size"
>
<AlternatingRowStyle />
<Columns>
<asp:BoundField
AccessibleHeaderText="string"
ApplyFormatInEditMode="True|False"
ConvertEmptyStringToNull="True|False"
DataField="string"
DataFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
HtmlEncode="True|False"
InsertVisible="True|False"
NullDisplayText="string"
ReadOnly="True|False"
ShowHeader="True|False"
SortExpression="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:BoundField>
<asp:ButtonField
AccessibleHeaderText="string"
ButtonType="Button|Image|Link"
CausesValidation="True|False"
CommandName="string"
DataTextField="string"
DataTextFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
ImageUrl="uri"
InsertVisible="True|False"
ShowHeader="True|False"
SortExpression="string"
Text="string"
ValidationGroup="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:ButtonField>
<asp:CheckBoxField
AccessibleHeaderText="string"
DataField="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertVisible="True|False"
ReadOnly="True|False"
ShowHeader="True|False"
SortExpression="string"
Text="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:CheckBoxField>
<asp:CommandField
AccessibleHeaderText="string"
ButtonType="Button|Image|Link"
CancelImageUrl="uri"
CancelText="string"
CausesValidation="True|False"
DeleteImageUrl="uri"
DeleteText="string"
EditImageUrl="uri"
EditText="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertImageUrl="uri"
InsertText="string"
InsertVisible="True|False"
NewImageUrl="uri"
NewText="string"
SelectImageUrl="uri"
SelectText="string"
ShowCancelButton="True|False"
ShowDeleteButton="True|False"
ShowEditButton="True|False"
ShowHeader="True|False"
ShowInsertButton="True|False"
ShowSelectButton="True|False"
SortExpression="string"
UpdateImageUrl="uri"
UpdateText="string"
ValidationGroup="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:CommandField>
<asp:DynamicField
AccessibleHeaderText="string"
ApplyFormatInEditMode="True|False"
ConvertEmptyStringToNull="True|False"
DataField="string"
DataFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
HtmlEncode="True|False"
InsertVisible="True|False"
NullDisplayText="string"
ShowHeader="True|False"
UIHint="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:DynamicField>
<asp:HyperLinkField
AccessibleHeaderText="string"
DataNavigateUrlFields="string"
DataNavigateUrlFormatString="string"
DataTextField="string"
DataTextFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertVisible="True|False"
NavigateUrl="uri"
ShowHeader="True|False"
SortExpression="string"
Target="string|_blank|_parent|_search|_self|_top"
Text="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:HyperLinkField>
<asp:ImageField
AccessibleHeaderText="string"
AlternateText="string"
ConvertEmptyStringToNull="True|False"
DataAlternateTextField="string"
DataAlternateTextFormatString="string"
DataImageUrlField="string"
DataImageUrlFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertVisible="True|False"
NullDisplayText="string"
NullImageUrl="uri"
ReadOnly="True|False"
ShowHeader="True|False"
SortExpression="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:ImageField>
<asp:TemplateField
AccessibleHeaderText="string"
ConvertEmptyStringToNull="True|False"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertVisible="True|False"
ShowHeader="True|False"
SortExpression="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
<AlternatingItemTemplate>
<!-- child controls -->
</AlternatingItemTemplate>
<EditItemTemplate>
<!-- child controls -->
</EditItemTemplate>
<FooterTemplate>
<!-- child controls -->
</FooterTemplate>
<HeaderTemplate>
<!-- child controls -->
</HeaderTemplate>
<InsertItemTemplate>
<!-- child controls -->
</InsertItemTemplate>
<ItemTemplate>
<!-- child controls -->
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle />
<EmptyDataRowStyle />
<EmptyDataTemplate>
<!-- child controls -->
</EmptyDataTemplate>
<FooterStyle />
<HeaderStyle />
<PagerSettings
FirstPageImageUrl="uri"
FirstPageText="string"
LastPageImageUrl="uri"
LastPageText="string"
Mode="NextPrevious|Numeric|NextPreviousFirstLast|
NumericFirstLast"
NextPageImageUrl="uri"
NextPageText="string"
OnPropertyChanged="PropertyChanged event handler"
PageButtonCount="integer"
Position="Bottom|Top|TopAndBottom"
PreviousPageImageUrl="uri"
PreviousPageText="string"
Visible="True|False"
/>
<PagerStyle />
<PagerTemplate>
<!-- child controls -->
</PagerTemplate>
<RowStyle />
<SelectedRowStyle />
</asp:GridView>

Examples
A Visual Studio Web site project with source code is available to accompany this topic: Download. The following example demonstrates how use the GridView control to display the values from the Customers table of the AdventureWorksLT sample database in Microsoft SQL Server. The values are retrieved using a SqlDataSource control.
<asp:sqldatasource id="CustomersSource"
selectcommand="SELECT CustomerID, CompanyName, FirstName, LastName FROM SalesLT.Customer"
connectionstring="<%$ ConnectionStrings:AWLTConnectionString %>"
runat="server"/>
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="False"
emptydatatext="No data available."
allowpaging="True"
runat="server" DataKeyNames="CustomerID">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
InsertVisible="False" ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
</Columns>
</asp:gridview>
<asp:sqldatasource id="CustomersSource"
selectcommand="SELECT CustomerID, CompanyName, FirstName, LastName FROM SalesLT.Customer"
connectionstring="<%$ ConnectionStrings:AWLTConnectionString %>"
runat="server"/>
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="False"
emptydatatext="No data available."
allowpaging="True"
runat="server" DataKeyNames="CustomerID">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
InsertVisible="False" ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
</Columns>
</asp:gridview>
The following example demonstrates how to use the GridView control and a LinqDataSource control so that you can edit records.
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="AdventureWorksLTDataClassesDataContext"
EnableDelete="True" EnableInsert="True" EnableUpdate="True"
TableName="SalesOrderDetails">
</asp:LinqDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="SalesOrderID,SalesOrderDetailID"
DataSourceID="LinqDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True"
ShowEditButton="True" />
<asp:BoundField DataField="SalesOrderID"
HeaderText="SalesOrderID" ReadOnly="True"
SortExpression="SalesOrderID" />
<asp:BoundField DataField="SalesOrderDetailID"
HeaderText="SalesOrderDetailID" InsertVisible="False"
ReadOnly="True" SortExpression="SalesOrderDetailID" />
<asp:BoundField DataField="OrderQty"
HeaderText="OrderQty" SortExpression="OrderQty" />
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" SortExpression="ProductID" />
<asp:BoundField DataField="UnitPrice"
HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="ModifiedDate"
HeaderText="ModifiedDate" SortExpression="ModifiedDate" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="AdventureWorksLTDataClassesDataContext"
EnableDelete="True" EnableInsert="True" EnableUpdate="True"
TableName="SalesOrderDetails">
</asp:LinqDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="SalesOrderID,SalesOrderDetailID"
DataSourceID="LinqDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True"
ShowEditButton="True" />
<asp:BoundField DataField="SalesOrderID"
HeaderText="SalesOrderID" ReadOnly="True"
SortExpression="SalesOrderID" />
<asp:BoundField DataField="SalesOrderDetailID"
HeaderText="SalesOrderDetailID" InsertVisible="False"
ReadOnly="True" SortExpression="SalesOrderDetailID" />
<asp:BoundField DataField="OrderQty"
HeaderText="OrderQty" SortExpression="OrderQty" />
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" SortExpression="ProductID" />
<asp:BoundField DataField="UnitPrice"
HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="ModifiedDate"
HeaderText="ModifiedDate" SortExpression="ModifiedDate" />
</Columns>
</asp:GridView>
For an example demonstrating how to access values in cells, see GridViewRow.

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, 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

Change History
|
Bibliothèque de classes .NET Framework GridView, classe Affiche les valeurs d'une source de données dans une table où chaque colonne représente un champ et chaque ligne représente un enregistrement. Le contrôle GridView vous permet de sélectionner, trier et modifier ces éléments.

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

Syntaxe
<ControlValuePropertyAttribute("SelectedValue")> _
Public Class GridView _
Inherits CompositeDataBoundControl _
Implements IPostBackContainer, IPostBackEventHandler, ICallbackContainer, ICallbackEventHandler, _
IPersistedSelector, IDataKeysControl, IDataBoundListControl, IDataBoundControl, IFieldControl
[ControlValuePropertyAttribute("SelectedValue")]
public class GridView : CompositeDataBoundControl, IPostBackContainer,
IPostBackEventHandler, ICallbackContainer, ICallbackEventHandler, IPersistedSelector, IDataKeysControl,
IDataBoundListControl, IDataBoundControl, IFieldControl
[ControlValuePropertyAttribute(L"SelectedValue")]
public ref class GridView : public CompositeDataBoundControl,
IPostBackContainer, IPostBackEventHandler, ICallbackContainer, ICallbackEventHandler, IPersistedSelector,
IDataKeysControl, IDataBoundListControl, IDataBoundControl, IFieldControl
[<ControlValuePropertyAttribute("SelectedValue")>]
type GridView =
class
inherit CompositeDataBoundControl
interface IPostBackContainer
interface IPostBackEventHandler
interface ICallbackContainer
interface ICallbackEventHandler
interface IPersistedSelector
interface IDataKeysControl
interface IDataBoundListControl
interface IDataBoundControl
interface IFieldControl
end
Le type GridView expose les membres suivants.

Constructeurs
|
| Nom | Description |
|---|
.gif) | GridView | Initialise une nouvelle instance de la classe GridView. | 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) | 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) | CreateAutoGeneratedColumn | Crée un champ de colonne généré automatiquement. | .gif) | CreateChildControls()()() | Infrastructure. Crée la hiérarchie des contrôles utilisée pour restituer un contrôle composite lié aux données basé sur les valeurs qui sont stockées dans l'état d'affichage. (Hérité de CompositeDataBoundControl.) | .gif) | CreateChildControls(IEnumerable, Boolean) | Infrastructure. Crée la hiérarchie des contrôles utilisée pour rendre le contrôle GridView à l'aide de la source de données spécifiée. (Substitue CompositeDataBoundControl..::.CreateChildControls(IEnumerable, Boolean).) | .gif) | CreateChildTable | Infrastructure. Crée une table enfant. | .gif) | CreateColumns | Crée le jeu de champs de colonnes utilisé pour générer la hiérarchie des contrôles. | .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 | Infrastructure. Crée le style par défaut du contrôle. (Substitue WebControl..::.CreateControlStyle()()().) | .gif) | CreateDataSourceSelectArguments | Crée l'objet DataSourceSelectArguments qui contient les arguments passés à la source de données pour être traités. (Substitue DataBoundControl..::.CreateDataSourceSelectArguments()()().) | .gif) | CreateRow | Crée une ligne de pagineur dans le contrôle GridView. | .gif) | DataBind()()() | Lie la source de données au contrôle GridView. Cette méthode ne peut pas être héritée. (Substitue BaseDataBoundControl..::.DataBind()()().) | .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) | DeleteRow | 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) | Equals(Object) | Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.) | .gif) | ExtractRowValues | Récupère les valeurs de chaque champ déclarées dans la ligne spécifiée 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) | Focus | Affecte le focus d'entrée à un contrôle. (Hérité de Control.) | .gif) | GetCallbackResult | Retourne le résultat d'un événement de rappel qui cible un contrôle. | .gif) | GetCallbackScript | Crée le script de rappel pour un bouton qui exécute une opération de tri. | .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) | InitializePager | Initialise la ligne de pagineur affichée lorsque la fonctionnalité de pagination est activée. | .gif) | InitializeRow | Initialise une ligne de pagineur dans le contrôle GridView. | .gif) | IsBindableType | Détermine si le type de données spécifié peut être lié à une colonne dans un contrôle GridView. | .gif) | IsLiteralContent | Infrastructure. Détermine si le contrôle serveur ne détient qu'un contenu littéral. (Hérité de Control.) | .gif) | LoadControlState | Infrastructure. Charge l'état des propriétés du contrôle GridView à faire persister, même lorsque la propriété Control..::.EnableViewState a la valeur false. (Substitue Control..::.LoadControlState(Object).) | .gif) | LoadViewState | Charge l'état d'affichage du contrôle GridView enregistré précédemment. (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 l'événement pour les contrôles serveur Web est passé dans la hiérarchie des contrôles serveur de l'interface utilisateur de la page. (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 GridView à ses données après la modification de la propriété DataMember, DataSource, ou DataSourceID. (Substitue DataBoundControl..::.OnDataPropertyChanged()()().) | .gif) | OnDataSourceViewChanged | Déclenche l'événement DataSourceViewChanged. (Substitue DataBoundControl..::.OnDataSourceViewChanged(Object, EventArgs).) | .gif) | OnInit | Déclenche l'événement Control..::.Init. (Substitue BaseDataBoundControl..::.OnInit(EventArgs).) | .gif) | OnLoad | Gère l'événement Control..::.Load. (Hérité de DataBoundControl.) | .gif) | OnPageIndexChanged | Déclenche l'événement PageIndexChanged. | .gif) | OnPageIndexChanging | Déclenche l'événement PageIndexChanging. | .gif) | OnPagePreLoad | Définit l'état initialisé du contrôle lié aux données avant que le contrôle ne soit chargé. (Substitue DataBoundControl..::.OnPagePreLoad(Object, EventArgs).) | .gif) | OnPreRender | Infrastructure. Déclenche l'événement PreRender. (Substitue BaseDataBoundControl..::.OnPreRender(EventArgs).) | .gif) | OnRowCancelingEdit | Déclenche l'événement RowCancelingEdit. | .gif) | OnRowCommand | Déclenche l'événement RowCommand. | .gif) | OnRowCreated | Déclenche l'événement RowCreated. | .gif) | OnRowDataBound | Déclenche l'événement RowDataBound. | .gif) | OnRowDeleted | Déclenche l'événement RowDeleted. | .gif) | OnRowDeleting | Déclenche l'événement RowDeleting. | .gif) | OnRowEditing | Déclenche l'événement RowEditing. | .gif) | OnRowUpdated | Déclenche l'événement RowUpdated. | .gif) | OnRowUpdating | Déclenche l'événement RowUpdating. | .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) | 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 | Infrastructure. Lie la source de données spécifiée au contrôle GridView. (Substitue CompositeDataBoundControl..::.PerformDataBinding(IEnumerable).) | .gif) | PerformSelect | Récupère les données de la source de données associée. (Hérité de DataBoundControl.) | .gif) | PrepareControlHierarchy | Infrastructure. Établit la hiérarchie des contrôles. | .gif) | RaiseBubbleEvent | Assigne les sources éventuelles de l'événement et ses informations au parent du contrôle. (Hérité de Control.) | .gif) | RaiseCallbackEvent | Crée les arguments du gestionnaire de rappel de la méthode GetCallbackEventReference. | .gif) | RaisePostBackEvent | Déclenche les événements appropriés pour le contrôle GridView lors de la publication sur le serveur. | .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) | Render | Infrastructure. Génère le rendu du contenu du contrôle serveur Web au navigateur du client à l'aide de l'objet System.Web.UI..::.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 | Infrastructure. Enregistre l'état des propriétés du contrôle GridView à faire persister, même lorsque la propriété Control..::.EnableViewState a la valeur false. (Substitue Control..::.SaveControlState()()().) | .gif) | SaveViewState | Infrastructure. Charge l'état d'affichage du contrôle GridView enregistré précédemment. (Substitue WebControl..::.SaveViewState()()().) | .gif) | SelectRow | Sélectionne la ligne à modifier dans un contrôle GridView. | .gif) | SetDesignModeState | Définit les données au moment du design pour un contrôle. (Hérité de Control.) | .gif) | SetEditRow | Met une ligne en mode édition dans un contrôle GridView en utilisant l'index de ligne spécifié. | .gif) | SetPageIndex | Définit l'index de page du contrôle GridView en utilisant l'index de ligne. | .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 GridView 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 | Infrastructure. Suit les modifications d'état d'affichage du contrôle GridView afin qu'elles puissent être stockées dans l'objet System.Web.UI..::.StateBag du contrôle. Cet objet est accessible via la propriété Control..::.ViewState. (Substitue WebControl..::.TrackViewState()()().) | .gif) | UpdateRow | Met à jour l'enregistrement à l'index de ligne spécifié à l'aide des valeurs de champ de la ligne. | .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) | Load | Se produit lorsque le contrôle serveur est chargé dans l'objet Page. (Hérité de Control.) | .gif) | PageIndexChanged | Se produit lorsqu'un clic est effectué sur un des boutons de pagineur, mais une fois que le contrôle GridView a géré l'opération de pagination. | .gif) | PageIndexChanging | Se produit lorsqu'un clic est effectué sur des boutons du pagineur et avant que le contrôle GridView n'ait géré l'opération de pagination. | .gif) | PreRender | Se produit après le chargement de l'objet Control mais avant le rendu. (Hérité de Control.) | .gif) | RowCancelingEdit | Se produit lorsqu'un clic est effectué sur le bouton Annuler d'une ligne en mode édition, mais avant que la ligne ne quitte le mode édition. | .gif) | RowCommand | Se produit lorsqu'un clic est effectué sur un bouton dans un contrôle GridView. | .gif) | RowCreated | Se produit lorsqu'une ligne est créée dans un contrôle GridView. | .gif) | RowDataBound | Se produit lorsqu'une ligne de données est liée aux données dans un contrôle GridView. | .gif) | RowDeleted | Se produit lorsqu'un clic est effectué sur le bouton Supprimer d'une ligne, mais après que le contrôle GridView a supprimé la ligne. | .gif) | RowDeleting | Se produit lorsqu'un clic est effectué sur le bouton Supprimer d'une ligne, mais avant que le contrôle GridView n'ait supprimé la ligne. | .gif) | RowEditing | Se produit lors d'un clic sur le bouton Modification d'une ligne, mais avant que le contrôle GridView ne passe en mode édition. | .gif) | RowUpdated | Se produit lors d'un clic sur le bouton Mise à jour d'une ligne, mais après que le contrôle GridView a mis la ligne à jour. | .gif) | RowUpdating | Se produit lors d'un clic sur le bouton Mise à jour d'une ligne, mais avant que le contrôle GridView ne mette la ligne à jour. | .gif) | SelectedIndexChanged | Se produit en cas de clic sur le bouton de sélection d'une ligne, mais après que le contrôle GridView a géré l'opération de sélection. | .gif) | SelectedIndexChanging | Se produit en cas de clic sur le bouton de sélection d'une ligne, mais avant que le contrôle GridView ne gère l'opération de sélection. | .gif) | Sorted | Se produit en cas de clic sur le lien hypertexte de tri d'une colonne, mais après que le contrôle GridView a géré l'opération de tri. | .gif) | Sorting | Se produit en cas de clic sur le lien hypertexte de tri d'une colonne, mais avant que le contrôle GridView 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) | ICallbackContainer..::.GetCallbackScript | Infrastructure. Crée le script de rappel pour un bouton qui exécute une opération de tri. | .gif) .gif) | ICallbackEventHandler..::.GetCallbackResult | Infrastructure. Retourne le résultat d'un événement de rappel qui cible un contrôle. | .gif) .gif) | ICallbackEventHandler..::.RaiseCallbackEvent | Infrastructure. Crée les arguments du gestionnaire de rappel de la méthode GetCallbackEventReference. | .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 les noms des champs clés primaires pour les éléments affichés dans un contrôle lié aux données. | .gif) .gif) | IDataBoundControl..::.DataMember | Obtient ou définit le tableau exposé par le contrôle de source de données à lier au contrôle lié aux données. | .gif) .gif) | IDataBoundControl..::.DataSource | Obtient ou définit l'objet source de données duquel le contrôle lié aux données récupère la liste d'éléments de données. | .gif) .gif) | IDataBoundControl..::.DataSourceID | Obtient ou définit l'ID de la source de données de laquelle le contrôle lié aux données récupère la liste d'éléments de données. | .gif) .gif) | IDataBoundControl..::.DataSourceObject | Obtient ou définit l'objet source de données duquel le contrôle lié aux données récupère la liste d'éléments de données. | .gif) .gif) | IDataBoundListControl..::.ClientIDRowSuffix | Obtient ou définit les noms des champs de données dont les valeurs sont ajoutées à la valeur de propriété ClientID pour identifier de façon unique chaque instance d'un contrôle lié aux données. | .gif) .gif) | IDataBoundListControl..::.DataKeys | Obtient une collection d'objets qui représentent la valeur DataKeys dans un contrôle lié aux données. | .gif) .gif) | IDataBoundListControl..::.EnablePersistedSelection | Obtient ou définit une valeur qui indique si la sélection d'une ligne est basée sur l'index ou sur les valeurs de clés de données. | .gif) .gif) | IDataBoundListControl..::.SelectedDataKey | Obtient l'objet qui contient la valeur de clés des 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 le contrôle lié aux données. | .gif) .gif) | IDataKeysControl..::.ClientIDRowSuffixDataKeys | Infrastructure. Obtient les 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) | IFieldControl..::.FieldsGenerator | Obtient ou définit le contrôle qui génère automatiquement les colonnes d'un contrôle lié aux données utilisées par Dynamic Data ASP.NET. | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | Pour obtenir une description de ce membre, consultez IParserAccessor..::.AddParsedSubObject. (Hérité de Control.) | .gif) .gif) | IPersistedSelector..::.DataKey | Pour obtenir une description de ce membre, consultez IPersistedSelector..::.DataKey. | .gif) .gif) | IPostBackContainer..::.GetPostBackOptions | Infrastructure. Crée un objet PostBackOptions qui représente le comportement de publication (postback) du contrôle bouton spécifié. | .gif) .gif) | IPostBackEventHandler..::.RaisePostBackEvent | Infrastructure. Déclenche les événements appropriés pour le contrôle GridView lors de la publication sur le serveur. | Début

Notes
Dans cette rubrique : IntroductionLe contrôle GridView est utilisé pour afficher les valeurs d'une source de données dans une table. Chaque colonne représente un champ tandis que chaque ligne représente un enregistrement. Le contrôle GridView prend en charge les fonctionnalités suivantes : Liaison aux contrôles de source de données, telle que SqlDataSource. Fonctionnalités intégrées de tri. Fonctionnalités intégrées de mise à jour et de suppression. Fonctionnalités intégrées de pagination. Fonctionnalités intégrées de sélection de ligne. Accès par programme au modèle objet GridView pour définir des propriétés de manière dynamique, gérer les événements, etc. Plusieurs champs clés. Plusieurs champs de données pour les colonnes de lien hypertexte. Apparence personnalisable via des thèmes et des styles. Pour en savoir plus sur les autres contrôles liés aux données, qui sont disponibles dans ASP.NET, consultez Vue d'ensemble des contrôles serveur Web liés aux données ASP.NET.
Remarque |
|---|
Si vous êtes familiarisé avec le contrôle DataGrid à partir de la version 1.0 du .NET Framework, le contrôle GridView succède au contrôle DataGrid. |
Champs de colonnesChaque colonne du contrôle GridView est représentée par un objet DataControlField. Par défaut, la propriété AutoGenerateColumns a la valeur true, qui crée un objet AutoGeneratedField pour chaque champ dans la source de données. Chaque champ est ensuite rendu sous forme de colonne dans le contrôle GridView dans l'ordre dans lequel chaque champ s'affiche dans la source de données. Vous pouvez aussi contrôler les colonnes qui doivent apparaître dans le contrôle GridView en définissant la propriété AutoGenerateColumns avec la valeur false et en définissant votre propre collection de champs de colonnes. Différents types de champs de colonnes déterminent le comportement des colonnes dans le contrôle. Le tableau suivant affiche les différents types de champs de colonnes qui peuvent être utilisés. Type de champ de colonne | Description |
|---|
BoundField
| Affiche la valeur d'un champ dans une source de données. Il s'agit du type de colonne par défaut du contrôle GridView. |
ButtonField
| Affiche un bouton de commande pour chaque élément dans le contrôle GridView. Cela vous permet de créer une colonne de contrôles bouton personnalisés, tels que les boutons Ajouter ou Supprimer. |
CheckBoxField
| Affiche une case à cocher pour chaque élément dans le contrôle GridView. Ce type de champ de colonne est couramment utilisé pour afficher les champs avec une valeur Boolean. |
CommandField
| Affiche des boutons de commande prédéfinis pour exécuter la sélection, la modification ou la suppression d'opérations. |
HyperLinkField
| Affiche la valeur d'un champ dans une source de données sous la forme de lien hypertexte. Ce type de champ de colonne vous permet de lier un deuxième champ à l'URL du lien hypertexte. |
ImageField
| Affiche une image pour chaque élément dans le contrôle GridView. |
TemplateField
| Affiche le contenu défini par l'utilisateur pour chaque élément dans le contrôle GridView en fonction d'un modèle spécifié. Ce type de champ de colonne vous permet de créer un champ de colonne personnalisé. |
Pour définir une collection de champs de colonnes de manière déclarative, ajoutez d'abord les balises <Columns> d'ouverture et de fermeture entre les balises d'ouverture et de fermeture du contrôle GridView. Ensuite, répertoriez les champs de colonnes que vous souhaitez inclure entre les balises d'ouverture et de fermeture <Columns>. Les colonnes spécifiées sont ajoutées à la collection Columns dans l'ordre répertorié. La collection Columns stocke tous les champs de colonnes dans le contrôle et vous permet de gérer par programme les champs de colonnes dans le contrôle GridView. Les champs de colonnes déclarés explicitement peuvent être affichés dans une combinaison de champs de colonnes générés automatiquement. Lorsque vous utilisez les deux types de colonnes, les champs de colonnes déclarés explicitement sont rendus en premier, suivis des champs de colonnes générés automatiquement. Remarque |
|---|
Les champs de colonnes générés automatiquement ne sont pas ajoutés à la collection Columns. |
Liaison de donnéesLe contrôle GridView 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 GridView 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 GridView la valeur ID du contrôle de source de données. Le contrôle GridView lie automatiquement le 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 les fonctionnalités de tri, 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 source de données à la propriété DataSource du contrôle GridView, puis appelez la méthode DataBind. Lors de l'utilisation de cette méthode, le contrôle GridView 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 |
|---|
Ce contrôle peut être utilisé pour afficher des entrées d'utilisateur qui peuvent inclure un script client nuisible. Recherchez dans toutes les informations envoyées par un client un script exécutable, des instructions SQL ou d'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 d'être affichées dans ce contrôle (la classe BoundField code en HTML les valeurs par défaut). ASP.NET fournit une fonctionnalité de validation de demande d'entrée pour bloquer les scripts et le HTML dans les entrées d'utilisateur (user input). Des contrôles serveur de validation sont également fournis pour valider les entrées d'utilisateur (user input). Pour plus d'informations, consultez Introduction to the Validation Controls. |
Opérations de donnéesLe contrôle GridView fournit plusieurs fonctionnalités intégrées qui permettent à l'utilisateur de trier, mettre à jour, supprimer, sélectionner et parcourir les éléments dans le contrôle. Lorsque le contrôle GridView est lié à un contrôle de source de données, le contrôle GridView peut tirer parti des fonctionnalités du contrôle de source de données et fournir les fonctionnalités automatiques de tri, de mise à jour et de suppression. Remarque |
|---|
Le contrôle GridView peut fournir l'assistance pour trier, mettre à jour et supprimer avec d'autres types de sources de données. Toutefois, vous devrez fournir, avec l'implémentation, un gestionnaire d'événements approprié pour ces opérations. |
Le tri permet à l'utilisateur de trier les éléments dans le contrôle GridView conformément à une colonne particulière en cliquant sur l'en-tête de la colonne. Pour activer le tri, affectez la valeur true à la propriété AllowSorting. Les fonctionnalités automatiques de mise à jour, de suppression et de sélection sont activées lorsque vous cliquez sur le bouton d'un champ de colonne ButtonField ou TemplateField portant le nom de commande "Modifier", "Supprimer" et "Sélectionner" respectivement. Le contrôle GridView peut ajouter automatiquement un champ de colonne CommandField avec le bouton Modifier, Supprimer ou Sélectionner, respectivement, si la propriété AutoGenerateEditButton, AutoGenerateDeleteButton ou AutoGenerateSelectButton a la valeur true. Remarque |
|---|
L'insertion d'enregistrements dans la source de données n'est pas prise en charge directement par le contrôle GridView. Toutefois, il est possible d'insérer des enregistrements à l'aide du contrôle GridView conjointement avec le contrôle DetailsView ou FormView. Pour plus d'informations, consultez DetailsView ou FormView, respectivement. |
Au lieu d'afficher en même temps tous les enregistrements dans la source de données, le contrôle GridView peut scinder automatiquement les enregistrements en pages. Pour activer la pagination, attribuez la valeur true à la propriété AllowPaging. Remarque |
|---|
Le contrôle GridView est recréé lors de la publication (postback) en fonction des informations stockées dans ViewState. Si le contrôle GridView inclut un TemplateField ou un CommandField dont la propriété CausesValidation a la valeur true, la propriété EnableViewState doit également avoir la valeur true pour garantir que les opérations de données simultanées, telles que les mises à jour et les suppressions, s'appliquent à la ligne appropriée. |
Personnalisation de l'interface utilisateurVous pouvez personnaliser l'apparence du contrôle GridView en définissant les propriétés de style des différentes parties du contrôle. Le tableau suivant énumère les différentes propriétés de style. Propriété de style | Description |
|---|
AlternatingRowStyle
| Paramètres de style pour les lignes de données en alternance dans le contrôle GridView. Lorsque cette propriété est définie, les lignes de données sont affichées en alternance entre les paramètres RowStyle et les paramètres AlternatingRowStyle. |
EditRowStyle
| Paramètres de style pour la ligne en cours d'édition dans le contrôle GridView. |
EmptyDataRowStyle
| Les paramètres de style de la ligne de données vide affichée dans le contrôle GridView lorsque la source de données ne contient pas d'enregistrements. |
FooterStyle
| Les paramètres de style pour la ligne de pied de page du contrôle GridView. |
HeaderStyle
| Les paramètres de style pour la ligne d'en-tête du contrôle GridView. |
PagerStyle
| Paramètres de style pour la ligne de pagineur dans le contrôle GridView. |
RowStyle
| Paramètres de style pour les lignes de données dans le contrôle GridView. Lorsque la propriété AlternatingRowStyle est également définie, les lignes de données sont affichées en alternance entre les paramètres RowStyle et les paramètres AlternatingRowStyle. |
SelectedRowStyle
| Paramètres de style pour la ligne sélectionnée dans le contrôle GridView. |
SortedAscendingCellStyle
| Le paramètre de style pour la colonne de données par laquelle les données sont triées dans le contrôle GridView. Lorsque ce style est défini, le style (par exemple, colonne en surbrillance) est appliqué aux cellules lorsque les données sont triées dans l'ordre croissant. |
SortedAscendingHeaderStyle
| Le paramètre de style pour la colonne de données par laquelle les données sont triées dans le contrôle GridView. Lorsque ce style est défini, une flèche qui indique que les données sont triées dans l'ordre croissant est placée sur l'en-tête du contrôle GridView lorsque les données sont triées dans l'ordre croissant. |
SortedDescendingCellStyle
| Le paramètre de style pour la colonne de données par laquelle les données sont triées dans le contrôle GridView. Lorsque ce style est défini, le style (par exemple, colonne en surbrillance) est appliqué aux cellules lorsque les données sont triées dans l'ordre décroissant. |
SortedDescendingHeaderStyle
| Le paramètre de style pour la colonne de données par laquelle les données sont triées dans le contrôle GridView. Lorsque ce style est défini, une flèche qui pointe vers le bas est placée sur l'en-tête de GridView lorsque les données sont triées dans l'ordre décroissant. |
Vous pouvez également afficher ou masquer différentes parties du contrôle. Le tableau suivant énumère les propriétés qui contrôlent les parties qui sont affichées ou masquées. Propriété | Description |
|---|
ShowFooter
| Affiche ou masque la section de pied de page du contrôle GridView. |
ShowHeader
| Affiche ou masque la section d'en-tête du contrôle GridView. |
ÉvénementsLe contrôle GridView fournit plusieurs événements que vous pouvez programmer. Cela vous permet d'exécuter une routine personnalisée lorsqu'un événement se produit. Le tableau suivant répertorie les événements qui sont pris en charge par le contrôle GridView. Événement | Description |
|---|
PageIndexChanged
| Se produit lorsqu'un clic est effectué sur un des boutons de pagineur, mais une fois que le contrôle GridView a géré l'opération de pagination. Cet événement est couramment utilisé lorsque vous devez exécuter une tâche une fois que l'utilisateur a navigué vers une page différente dans le contrôle. |
PageIndexChanging
| Se produit lorsqu'un clic est effectué sur des boutons du pagineur et avant que le contrôle GridView n'ait géré l'opération de pagination. Cet événement est souvent utilisé pour annuler l'opération de pagination. |
RowCancelingEdit
| Se produit lorsque l'utilisateur clique sur le bouton Annuler d'une ligne, mais avant que le contrôle GridView ne quitte le mode édition. Cet événement est souvent utilisé pour arrêter l'opération d'annulation. |
RowCommand
| Se produit lors d'un clic sur le bouton d'un contrôle GridView. Cet événement est souvent utilisé pour exécuter une tâche lorsqu'un clic est effectué dans le contrôle. |
RowCreated
| Se produit lorsqu'une ligne est créée dans le contrôle GridView. Cet événement est souvent utilisé pour modifier le contenu d'une ligne lorsque la ligne est créée. |
RowDataBound
| Se produit lorsqu'une ligne de données est liée aux données dans le contrôle GridView. Cet événement est souvent utilisé pour modifier le contenu d'une ligne lorsque la ligne est liée aux données. |
RowDeleted
| Se produit lorsque l'utilisateur clique sur le bouton Supprimer d'une ligne, mais une fois que le contrôle GridView a supprimé l'enregistrement de la source de données. Cet événement est souvent utilisé pour vérifier les résultats de l'opération de suppression. |
RowDeleting
| Se produit lorsque l'utilisateur clique sur le bouton Supprimer d'une ligne, mais avant que le contrôle GridView n'ait supprimé l'enregistrement de la source de données. Cet événement est souvent utilisé pour annuler l'opération de suppression. |
RowEditing
| Se produit lors d'un clic sur le bouton Modification d'une ligne, mais avant que le contrôle GridView ne passe en mode édition. Cet événement est souvent utilisé pour annuler l'opération de modification. |
RowUpdated
| Se produit lors d'un clic sur le bouton Mise à jour d'une ligne, mais après que le contrôle GridView a mis la ligne à jour. Cet événement est souvent utilisé pour vérifier les résultats de l'opération de mise à jour. |
RowUpdating
| Se produit lors d'un clic sur le bouton Mise à jour d'une ligne, mais avant que le contrôle GridView ne mette la ligne à jour. Cet événement est souvent utilisé pour annuler l'opération de mise à jour. |
SelectedIndexChanged
| Se produit en cas de clic sur le bouton de sélection d'une ligne, mais après que le contrôle GridView a géré l'opération de sélection. Cet événement est souvent utilisé pour exécuter une tâche lorsqu'une ligne est sélectionnée dans le contrôle. |
SelectedIndexChanging
| Se produit en cas de clic sur le bouton de sélection d'une ligne, mais avant que le contrôle GridView ne gère l'opération de sélection. Cet événement est souvent utilisé pour annuler l'opération de sélection. |
Sorted
| Se produit en cas de clic sur le lien hypertexte de tri d'une colonne, mais après que le contrôle GridView a géré l'opération de tri. Cet événement est couramment utilisé pour exécuter une tâche une fois que l'utilisateur a cliqué sur un lien hypertexte pour trier une colonne. |
Sorting
| Se produit en cas de clic sur le lien hypertexte de tri d'une colonne, mais avant que le contrôle GridView ne gère 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é. |
AccessibilitéSyntaxe déclarative
<asp:GridView
AccessKey="string"
AllowPaging="True|False"
AllowSorting="True|False"
AutoGenerateColumns="True|False"
AutoGenerateDeleteButton="True|False"
AutoGenerateEditButton="True|False"
AutoGenerateSelectButton="True|False"
BackColor="color name|#dddddd"
BackImageUrl="uri"
BorderColor="color name|#dddddd"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset"
BorderWidth="size"
Caption="string"
CaptionAlign="NotSet|Top|Bottom|Left|Right"
CellPadding="integer"
CellSpacing="integer"
CssClass="string"
DataKeyNames="string"
DataMember="string"
DataSource="string"
DataSourceID="string"
EditIndex="integer"
EmptyDataText="string"
Enabled="True|False"
EnableSortingAndPagingCallbacks="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
GridLines="None|Horizontal|Vertical|Both"
Height="size"
HorizontalAlign="NotSet|Left|Center|Right|Justify"
ID="string"
OnDataBinding="DataBinding event handler"
OnDataBound="DataBound event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnLoad="Load event handler"
OnPageIndexChanged="PageIndexChanged event handler"
OnPageIndexChanging="PageIndexChanging event handler"
OnPreRender="PreRender event handler"
OnRowCancelingEdit="RowCancelingEdit event handler"
OnRowCommand="RowCommand event handler"
OnRowCreated="RowCreated event handler"
OnRowDataBound="RowDataBound event handler"
OnRowDeleted="RowDeleted event handler"
OnRowDeleting="RowDeleting event handler"
OnRowEditing="RowEditing event handler"
OnRowUpdated="RowUpdated event handler"
OnRowUpdating="RowUpdating event handler"
OnSelectedIndexChanged="SelectedIndexChanged event handler"
OnSelectedIndexChanging="SelectedIndexChanging event handler"
OnSorted="Sorted event handler"
OnSorting="Sorting event handler"
OnUnload="Unload event handler"
PageIndex="integer"
PagerSettings-FirstPageImageUrl="uri"
PagerSettings-FirstPageText="string"
PagerSettings-LastPageImageUrl="uri"
PagerSettings-LastPageText="string"
PagerSettings-Mode="NextPrevious|Numeric|NextPreviousFirstLast|
NumericFirstLast"
PagerSettings-NextPageImageUrl="uri"
PagerSettings-NextPageText="string"
PagerSettings-PageButtonCount="integer"
PagerSettings-Position="Bottom|Top|TopAndBottom"
PagerSettings-PreviousPageImageUrl="uri"
PagerSettings-PreviousPageText="string"
PagerSettings-Visible="True|False"
PageSize="integer"
RowHeaderColumn="string"
runat="server"
SelectedIndex="integer"
ShowFooter="True|False"
ShowHeader="True|False"
SkinID="string"
Style="string"
TabIndex="integer"
ToolTip="string"
UseAccessibleHeader="True|False"
Visible="True|False"
Width="size"
>
<AlternatingRowStyle />
<Columns>
<asp:BoundField
AccessibleHeaderText="string"
ApplyFormatInEditMode="True|False"
ConvertEmptyStringToNull="True|False"
DataField="string"
DataFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
HtmlEncode="True|False"
InsertVisible="True|False"
NullDisplayText="string"
ReadOnly="True|False"
ShowHeader="True|False"
SortExpression="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:BoundField>
<asp:ButtonField
AccessibleHeaderText="string"
ButtonType="Button|Image|Link"
CausesValidation="True|False"
CommandName="string"
DataTextField="string"
DataTextFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
ImageUrl="uri"
InsertVisible="True|False"
ShowHeader="True|False"
SortExpression="string"
Text="string"
ValidationGroup="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:ButtonField>
<asp:CheckBoxField
AccessibleHeaderText="string"
DataField="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertVisible="True|False"
ReadOnly="True|False"
ShowHeader="True|False"
SortExpression="string"
Text="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:CheckBoxField>
<asp:CommandField
AccessibleHeaderText="string"
ButtonType="Button|Image|Link"
CancelImageUrl="uri"
CancelText="string"
CausesValidation="True|False"
DeleteImageUrl="uri"
DeleteText="string"
EditImageUrl="uri"
EditText="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertImageUrl="uri"
InsertText="string"
InsertVisible="True|False"
NewImageUrl="uri"
NewText="string"
SelectImageUrl="uri"
SelectText="string"
ShowCancelButton="True|False"
ShowDeleteButton="True|False"
ShowEditButton="True|False"
ShowHeader="True|False"
ShowInsertButton="True|False"
ShowSelectButton="True|False"
SortExpression="string"
UpdateImageUrl="uri"
UpdateText="string"
ValidationGroup="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:CommandField>
<asp:DynamicField
AccessibleHeaderText="string"
ApplyFormatInEditMode="True|False"
ConvertEmptyStringToNull="True|False"
DataField="string"
DataFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
HtmlEncode="True|False"
InsertVisible="True|False"
NullDisplayText="string"
ShowHeader="True|False"
UIHint="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:DynamicField>
<asp:HyperLinkField
AccessibleHeaderText="string"
DataNavigateUrlFields="string"
DataNavigateUrlFormatString="string"
DataTextField="string"
DataTextFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertVisible="True|False"
NavigateUrl="uri"
ShowHeader="True|False"
SortExpression="string"
Target="string|_blank|_parent|_search|_self|_top"
Text="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:HyperLinkField>
<asp:ImageField
AccessibleHeaderText="string"
AlternateText="string"
ConvertEmptyStringToNull="True|False"
DataAlternateTextField="string"
DataAlternateTextFormatString="string"
DataImageUrlField="string"
DataImageUrlFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertVisible="True|False"
NullDisplayText="string"
NullImageUrl="uri"
ReadOnly="True|False"
ShowHeader="True|False"
SortExpression="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:ImageField>
<asp:TemplateField
AccessibleHeaderText="string"
ConvertEmptyStringToNull="True|False"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
InsertVisible="True|False"
ShowHeader="True|False"
SortExpression="string"
Visible="True|False"
>
<ControlStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
<AlternatingItemTemplate>
<!-- child controls -->
</AlternatingItemTemplate>
<EditItemTemplate>
<!-- child controls -->
</EditItemTemplate>
<FooterTemplate>
<!-- child controls -->
</FooterTemplate>
<HeaderTemplate>
<!-- child controls -->
</HeaderTemplate>
<InsertItemTemplate>
<!-- child controls -->
</InsertItemTemplate>
<ItemTemplate>
<!-- child controls -->
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle />
<EmptyDataRowStyle />
<EmptyDataTemplate>
<!-- child controls -->
</EmptyDataTemplate>
<FooterStyle />
<HeaderStyle />
<PagerSettings
FirstPageImageUrl="uri"
FirstPageText="string"
LastPageImageUrl="uri"
LastPageText="string"
Mode="NextPrevious|Numeric|NextPreviousFirstLast|
NumericFirstLast"
NextPageImageUrl="uri"
NextPageText="string"
OnPropertyChanged="PropertyChanged event handler"
PageButtonCount="integer"
Position="Bottom|Top|TopAndBottom"
PreviousPageImageUrl="uri"
PreviousPageText="string"
Visible="True|False"
/>
<PagerStyle />
<PagerTemplate>
<!-- child controls -->
</PagerTemplate>
<RowStyle />
<SelectedRowStyle />
</asp:GridView>

Exemples
Un projet de site Web Visual Studio contenant du code source est disponible pour accompagner cette rubrique : Download. L'exemple de code suivant montre comment utiliser le contrôle GridView pour afficher les valeurs de la table Customers de l'exemple de base de données AdventureWorksLT dans Microsoft SQL Server. Les valeurs sont récupérées à l'aide d'un contrôle SqlDataSource.
<asp:sqldatasource id="CustomersSource"
selectcommand="SELECT CustomerID, CompanyName, FirstName, LastName FROM SalesLT.Customer"
connectionstring="<%$ ConnectionStrings:AWLTConnectionString %>"
runat="server"/>
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="False"
emptydatatext="No data available."
allowpaging="True"
runat="server" DataKeyNames="CustomerID">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
InsertVisible="False" ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
</Columns>
</asp:gridview>
<asp:sqldatasource id="CustomersSource"
selectcommand="SELECT CustomerID, CompanyName, FirstName, LastName FROM SalesLT.Customer"
connectionstring="<%$ ConnectionStrings:AWLTConnectionString %>"
runat="server"/>
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="False"
emptydatatext="No data available."
allowpaging="True"
runat="server" DataKeyNames="CustomerID">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
InsertVisible="False" ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
</Columns>
</asp:gridview>
L'exemple suivant montre comment utiliser le contrôle GridView et un contrôle LinqDataSource pour modifier des enregistrements.
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="AdventureWorksLTDataClassesDataContext"
EnableDelete="True" EnableInsert="True" EnableUpdate="True"
TableName="SalesOrderDetails">
</asp:LinqDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="SalesOrderID,SalesOrderDetailID"
DataSourceID="LinqDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True"
ShowEditButton="True" />
<asp:BoundField DataField="SalesOrderID"
HeaderText="SalesOrderID" ReadOnly="True"
SortExpression="SalesOrderID" />
<asp:BoundField DataField="SalesOrderDetailID"
HeaderText="SalesOrderDetailID" InsertVisible="False"
ReadOnly="True" SortExpression="SalesOrderDetailID" />
<asp:BoundField DataField="OrderQty"
HeaderText="OrderQty" SortExpression="OrderQty" />
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" SortExpression="ProductID" />
<asp:BoundField DataField="UnitPrice"
HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="ModifiedDate"
HeaderText="ModifiedDate" SortExpression="ModifiedDate" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="AdventureWorksLTDataClassesDataContext"
EnableDelete="True" EnableInsert="True" EnableUpdate="True"
TableName="SalesOrderDetails">
</asp:LinqDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="SalesOrderID,SalesOrderDetailID"
DataSourceID="LinqDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True"
ShowEditButton="True" />
<asp:BoundField DataField="SalesOrderID"
HeaderText="SalesOrderID" ReadOnly="True"
SortExpression="SalesOrderID" />
<asp:BoundField DataField="SalesOrderDetailID"
HeaderText="SalesOrderDetailID" InsertVisible="False"
ReadOnly="True" SortExpression="SalesOrderDetailID" />
<asp:BoundField DataField="OrderQty"
HeaderText="OrderQty" SortExpression="OrderQty" />
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" SortExpression="ProductID" />
<asp:BoundField DataField="UnitPrice"
HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="ModifiedDate"
HeaderText="ModifiedDate" SortExpression="ModifiedDate" />
</Columns>
</asp:GridView>
Pour obtenir un exemple de code qui montre comment accéder aux valeurs des cellules, consultez GridViewRow.

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

Plateformes
Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, 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

Historique des modifications
|