.NET Framework Class Library GridViewRow Class Represents an individual row in a GridView control.

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

Syntax
Public Class GridViewRow _
Inherits TableRow _
Implements IDataItemContainer, INamingContainer
public class GridViewRow : TableRow,
IDataItemContainer, INamingContainer
public ref class GridViewRow : public TableRow,
IDataItemContainer, INamingContainer
type GridViewRow =
class
inherit TableRow
interface IDataItemContainer
interface INamingContainer
end
The GridViewRow type exposes the following members.

Constructors
|
| Name | Description |
|---|
.gif) | GridViewRow | Initializes a new instance of the GridViewRow 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) | CopyBaseAttributes | Copies the properties not encapsulated by the Style object from the specified Web server control to the Web server control that this method is called from. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | CreateChildControls | Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. (Inherited from Control.) | .gif) | CreateControlCollection | Creates a new ControlCollection object for the TableRow control. (Inherited from TableRow.) | .gif) | CreateControlStyle | Creates a TableItemStyle object for the TableRow control. (Inherited from TableRow.) | .gif) | DataBind()()() | Binds a data source to the invoked server control and all its child controls. (Inherited from Control.) | .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) | 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) | 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) | 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) | 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) | IsLiteralContent | Infrastructure. Determines if the server control holds only literal content. (Inherited from Control.) | .gif) | LoadControlState | Restores control-state information from a previous page request that was saved by the SaveControlState method. (Inherited from Control.) | .gif) | LoadViewState | Restores view-state information from a previous request that was saved with the SaveViewState method. (Inherited from WebControl.) | .gif) | MapPathSecure | Retrieves the physical path that a virtual path, either absolute or relative, maps to. (Inherited from Control.) | .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 to pass an event up the page's ASP.NET server control hierarchy. (Overrides Control..::.OnBubbleEvent(Object, EventArgs).) | .gif) | OnDataBinding | Raises the DataBinding event. (Inherited from Control.) | .gif) | OnInit | Raises the Init event. (Inherited from Control.) | .gif) | OnLoad | Raises the Load event. (Inherited from Control.) | .gif) | OnPreRender | Raises the PreRender event. (Inherited from Control.) | .gif) | OnUnload | Raises the Unload event. (Inherited from Control.) | .gif) | OpenFile | Gets a Stream used to read a file. (Inherited from Control.) | .gif) | RaiseBubbleEvent | Assigns any sources of the event and its information to the control's parent. (Inherited from Control.) | .gif) | RemovedControl | Called after a child control is removed from the Controls collection of the Control object. (Inherited from Control.) | .gif) | Render | Renders the control to the specified HTML writer. (Inherited from WebControl.) | .gif) | RenderBeginTag | Renders the HTML opening tag of the control to the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | RenderChildren | Outputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client. (Inherited from Control.) | .gif) | RenderContents | Renders the contents of the control to the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | RenderControl(HtmlTextWriter) | Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled. (Inherited from Control.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object. (Inherited from Control.) | .gif) | RenderEndTag | Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | ResolveAdapter | Gets the control adapter responsible for rendering the specified control. (Inherited from Control.) | .gif) | ResolveClientUrl | Gets a URL that can be used by the browser. (Inherited from Control.) | .gif) | ResolveUrl | Converts a URL into one that is usable on the requesting client. (Inherited from Control.) | .gif) | SaveControlState | Saves any server control state changes that have occurred since the time the page was posted back to the server. (Inherited from Control.) | .gif) | SaveViewState | Saves any state that was modified after the TrackViewState method was invoked. (Inherited from WebControl.) | .gif) | SetDesignModeState | Sets design-time data for a control. (Inherited from Control.) | .gif) | SetRenderMethodDelegate | Infrastructure. Assigns an event handler delegate to render the server control and its content into its parent control. (Inherited from Control.) | .gif) | ToString | Returns a string that represents the current object. (Inherited from Object.) | .gif) | TrackViewState | Causes the control to track changes to its view state so they can be stored in the object's ViewState property. (Inherited from WebControl.) | Top

Extension Methods

Explicit Interface Implementations
|
| Name | Description |
|---|
.gif) .gif) | IAttributeAccessor..::.GetAttribute | Infrastructure. Gets an attribute of the Web control with the specified name. (Inherited from WebControl.) | .gif) .gif) | IAttributeAccessor..::.SetAttribute | Sets an attribute of the Web control to the specified name and value. (Inherited from WebControl.) | .gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | For a description of this member, see IControlBuilderAccessor..::.ControlBuilder. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.GetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.SetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. For a description of this member, see IControlDesignerAccessor..::.SetOwnerControl. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | For a description of this member, see IControlDesignerAccessor..::.UserData. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | For a description of this member, see IDataBindingsAccessor..::.DataBindings. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | For a description of this member, see IDataBindingsAccessor..::.HasDataBindings. (Inherited from Control.) | .gif) .gif) | IDataItemContainer..::.DataItem | Infrastructure. For a description of this member, see DataItem. | .gif) .gif) | IDataItemContainer..::.DataItemIndex | Infrastructure. For a description of this member, see DataItemIndex. | .gif) .gif) | IDataItemContainer..::.DisplayIndex | Infrastructure. For a description of this member, see DisplayIndex. | .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) | IParserAccessor..::.AddParsedSubObject | For a description of this member, see IParserAccessor..::.AddParsedSubObject. (Inherited from Control.) | Top

Remarks
The GridViewRow class is used represent an individual row in a GridView control. Each row in the GridView control has a designated row type. The following table lists the different row types. Row type | Description |
|---|
DataControlRowType..::.DataRow | A data row in the GridView control. | DataControlRowType..::.EmptyDataRow | The empty row in the GridView control. The empty row is displayed when the GridView control has no records to display and the GridView..::.EmptyDataTemplate template is not nullNothingnullptra null reference (Nothing in Visual Basic). | DataControlRowType..::.Footer | The footer row in the GridView control. | DataControlRowType..::.Header | The header row in the GridView control. | DataControlRowType..::.Pager | A pager row in the GridView control. | DataControlRowType..::.Separator | A separator row in the GridView control. |
To determine the row type of a GridViewRow object, use the RowType property. A GridViewRow object also has a state associated with it. The state can be a bitwise combination of the values in the following table. State value | Description |
|---|
DataControlRowState..::.Alternate | The GridViewRow object is an alternate row in the GridView control. | DataControlRowState..::.Edit | The GridViewRow object is in edit mode. | DataControlRowState..::.Normal | The GridViewRow object is in its normal (default) state. | DataControlRowState..::.Selected | The GridViewRow object is selected. |
To determine the state of a GridViewRow object, use the RowState property. The GridView control stores all of its data rows in the Rows collection. To determine the index of a GridViewRow object in the Rows collection, use the RowIndex property. You can access the properties of the underlying data object that is bound to the GridViewRow object by using the DataItem property. To determine the index of the data object in the underlying data source, use the DataItemIndex property. You can access the individual cells of the GridViewRow object by using the Cells property. If a cell contains other controls, you can retrieve a control from the cell by using the Controls collection of the cell. You can also use the FindControl method of the cell to find the control, if the control has an ID specified. To retrieve a field value from a BoundField field column or an automatically generated field column, use the Text property of the cell. To retrieve a field value from other field column types where the field value is bound to a control, first retrieve the control from the appropriate cell and then access the appropriate property of the control. Note |
|---|
It is possible to use a data-binding expression directly in a TemplateField field column without binding the value to a property of a control. In this case, the field value is automatically placed in a DataBoundLiteralControl control. To retrieve the field value, you must first retrieve the DataBoundLiteralControl control from the appropriate cell and then use its Text property. |
For a list of initial property values for an instance of GridViewRow, see the GridViewRow constructor.

Examples
The following example demonstrates how to use a GridViewRow object to retrieve a field value from a cell in the GridView control and then display the value on the page.
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub AuthorsGridView_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
' Get the selected row from the GridView control.
Dim selectRow As GridViewRow = AuthorsGridView.SelectedRow
' Get the author's first and last name from the appropriate
' cells in the selected row. For BoundField field columns
' and automatically generated field columns, the Text property
' of a cell is used to access a field value.
Dim lastName As String = selectRow.Cells(1).Text
' In a TemplateField column where a data-binding expression
' is used directly in the ItemTemplate, the field value
' is automatically placed in DataBoundLiteral control.
' Retrieve the DataBoundLiteral control from the cell. The
' DataBoundLiteral control is the first control in the
' Controls collection.
Dim firstNameLiteral As DataBoundLiteralControl = CType(selectRow.Cells(2).Controls(0), DataBoundLiteralControl)
Dim firstName As String = firstNameLiteral.Text
' Display the name of the selected author.
Message.Text = "You selected " & firstName & " " & lastName & "."
End Sub
</script>
<html >
<head runat="server">
<title>GridViewRow Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridViewRow Example</h3>
<asp:label id="Message"
forecolor="Red"
runat="server"/>
<br/>
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateselectbutton="true"
onselectedindexchanged="AuthorsGridView_SelectedIndexChanged"
runat="server">
<columns>
<asp:boundfield datafield="au_lname"
headertext="Last Name"/>
<asp:templatefield headertext="FirstName">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_lname], [au_fname], [address], [city], [state], [zip], [contract] FROM [authors]"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void AuthorsGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the selected row from the GridView control.
GridViewRow selectRow = AuthorsGridView.SelectedRow;
// Get the author's first and last name from the appropriate
// cells in the selected row. For BoundField field columns
// and automatically generated field columns, the Text property
// of a cell is used to access a field value.
String lastName = selectRow.Cells[1].Text;
// In a TemplateField column where a data-binding expression
// is used directly in the ItemTemplate, the field value
// is automatically placed in DataBoundLiteral control.
// Retrieve the DataBoundLiteral control from the cell. The
// DataBoundLiteral control is the first control in the
// Controls collection.
DataBoundLiteralControl firstNameLiteral = (DataBoundLiteralControl)selectRow.Cells[2].Controls[0];
String firstName = firstNameLiteral.Text;
// Display the name of the selected author.
Message.Text = "You selected " + firstName + " " + lastName + ".";
}
</script>
<html >
<head runat="server">
<title>GridViewRow Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridViewRow Example</h3>
<asp:label id="Message"
forecolor="Red"
runat="server"/>
<br/>
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateselectbutton="true"
onselectedindexchanged="AuthorsGridView_SelectedIndexChanged"
runat="server">
<columns>
<asp:boundfield datafield="au_lname"
headertext="Last Name"/>
<asp:templatefield headertext="FirstName">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_lname], [au_fname], [address], [city], [state], [zip], [contract] FROM [authors]"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
The following example demonstrates how to use a GridViewRow object to retrieve a TextBox control declared in a TemplateField field column's edit item template. The value of the text box is then passed to a SqlDataSource control for updating in the data source. Security Note |
|---|
This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview. |
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub AuthorsGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
' In this example, the GridView control will not automatically extract
' updated values from TemplateField column fields because they are not
' using a two-way binding expression. So, the updated
' values must be added manually to the NewValues dictionary.
' Get the GridViewRow object that represents the row being edited
' from the Rows collection of the GridView control.
Dim index As Integer = AuthorsGridView.EditIndex
Dim row As GridViewRow = AuthorsGridView.Rows(index)
' Get the controls that contain the updated values. In this
' example, the updated values are contained in the TextBox
' controls declared in the EditItemTemplates of the TemplateField
' column fields in the GridView control.
Dim lastName As TextBox = CType(row.FindControl("LastNameTextBox"), TextBox)
Dim firstName As TextBox = CType(row.FindControl("FirstNameTextBox"), TextBox)
' Add the updated values to the NewValues dictionary. Use the
' parameter names declared in the parameterized update query
' string for the key names.
e.NewValues("au_lname") = lastName.Text
e.NewValues("au_fname") = firstName.Text
End Sub
</script>
<html >
<head runat="server">
<title>GridViewRow Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridViewRow Example</h3>
<!-- The GridView control automatically sets the columns -->
<!-- specified in the datakeynames attribute as read-only -->
<!-- No input controls are rendered for these columns in -->
<!-- edit mode. -->
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
datakeynames="au_id"
cellpadding="10"
onrowupdating="AuthorsGridView_RowUpdating"
runat="server">
<columns>
<asp:boundfield datafield="au_id"
headertext="Author ID"
readonly="true"/>
<asp:templatefield headertext="Last Name"
itemstyle-verticalalign="Top">
<itemtemplate>
<%#Eval("au_lname")%>
</itemtemplate>
<edititemtemplate>
<asp:textbox id="LastNameTextBox"
text='<%#Eval("au_lname")%>'
width="90"
runat="server"/>
<br/>
<asp:requiredfieldvalidator id="LastNameRequiredValidator"
controltovalidate="LastNameTextBox"
display="Dynamic"
text="Please enter a last name."
runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:templatefield headertext="First Name"
itemstyle-verticalalign="Top">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
<edititemtemplate>
<asp:textbox id="FirstNameTextBox"
text='<%#Eval("au_fname")%>'
width="90"
runat="server"/>
<br/>
<asp:requiredfieldvalidator id="FirstNameRequiredValidator"
controltovalidate="FirstNameTextBox"
display="Dynamic"
text="Please enter a first name."
runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:checkboxfield datafield="contract"
headertext="Contract"
readonly="true"/>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_id], [au_lname], [au_fname], [contract] FROM [authors]"
updatecommand="UPDATE authors SET au_lname=@au_lname, au_fname=@au_fname WHERE (authors.au_id = @au_id)"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void AuthorsGridView_RowUpdating (Object sender, GridViewUpdateEventArgs e)
{
// In this example, the GridView control will not automatically extract
// updated values from TemplateField column fields because they are not
// using a two-way binding expression. So, the updated
// values must be added manually to the NewValues dictionary.
// Get the GridViewRow object that represents the row being edited
// from the Rows collection of the GridView control.
int index = AuthorsGridView.EditIndex;
GridViewRow row = AuthorsGridView.Rows[index];
// Get the controls that contain the updated values. In this
// example, the updated values are contained in the TextBox
// controls declared in the EditItemTemplates of the TemplateField
// column fields in the GridView control.
TextBox lastName = (TextBox)row.FindControl("LastNameTextBox");
TextBox firstName = (TextBox)row.FindControl("FirstNameTextBox");
// Add the updated values to the NewValues dictionary. Use the
// parameter names declared in the parameterized update query
// string for the key names.
e.NewValues["au_lname"] = lastName.Text;
e.NewValues["au_fname"] = firstName.Text;
}
</script>
<html >
<head runat="server">
<title>GridViewRow Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridViewRow Example</h3>
<!-- The GridView control automatically sets the columns -->
<!-- specified in the datakeynames attribute as read-only -->
<!-- No input controls are rendered for these columns in -->
<!-- edit mode. -->
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
datakeynames="au_id"
cellpadding="10"
onrowupdating="AuthorsGridView_RowUpdating"
runat="server">
<columns>
<asp:boundfield datafield="au_id"
headertext="Author ID"
readonly="true"/>
<asp:templatefield headertext="Last Name"
itemstyle-verticalalign="Top">
<itemtemplate>
<%#Eval("au_lname")%>
</itemtemplate>
<edititemtemplate>
<asp:textbox id="LastNameTextBox"
text='<%#Eval("au_lname")%>'
width="90"
runat="server"/>
<br/>
<asp:requiredfieldvalidator id="LastNameRequiredValidator"
controltovalidate="LastNameTextBox"
display="Dynamic"
text="Please enter a last name."
runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:templatefield headertext="First Name"
itemstyle-verticalalign="Top">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
<edititemtemplate>
<asp:textbox id="FirstNameTextBox"
text='<%#Eval("au_fname")%>'
width="90"
runat="server"/>
<br/>
<asp:requiredfieldvalidator id="FirstNameRequiredValidator"
controltovalidate="FirstNameTextBox"
display="Dynamic"
text="Please enter a first name."
runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:checkboxfield datafield="contract"
headertext="Contract"
readonly="true"/>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_id], [au_lname], [au_fname], [contract] FROM [authors]"
updatecommand="UPDATE authors SET au_lname=@au_lname, au_fname=@au_fname WHERE (authors.au_id = @au_id)"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>

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
|
Bibliothèque de classes .NET Framework GridViewRow, classe Représente une ligne individuelle dans un contrôle GridView.

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

Syntaxe
Public Class GridViewRow _
Inherits TableRow _
Implements IDataItemContainer, INamingContainer
public class GridViewRow : TableRow,
IDataItemContainer, INamingContainer
public ref class GridViewRow : public TableRow,
IDataItemContainer, INamingContainer
type GridViewRow =
class
inherit TableRow
interface IDataItemContainer
interface INamingContainer
end
Le type GridViewRow expose les membres suivants.

Constructeurs
|
| Nom | Description |
|---|
.gif) | GridViewRow | Initialise une nouvelle instance de la classe GridViewRow. | 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) | CopyBaseAttributes | Copie les propriétés non encapsulées par l'objet Style du contrôle serveur Web spécifié vers le contrôle serveur Web à partir duquel cette méthode est appelée. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | CreateChildControls | Appelé par l'infrastructure de page ASP.NET pour avertir les contrôles serveur qui utilisent une implémentation basée sur la composition qu'ils doivent créer tous les contrôles enfants qu'ils contiennent en préparation de la publication ou du rendu. (Hérité de Control.) | .gif) | CreateControlCollection | Crée un nouvel objet ControlCollection pour le contrôle TableRow. (Hérité de TableRow.) | .gif) | CreateControlStyle | Crée un objet TableItemStyle pour le contrôle TableRow. (Hérité de TableRow.) | .gif) | DataBind()()() | Lie une source de données au contrôle serveur appelé et à tous ses contrôles enfants. (Hérité de Control.) | .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) | 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) | 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) | 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) | 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) | IsLiteralContent | Infrastructure. Détermine si le contrôle serveur ne détient qu'un contenu littéral. (Hérité de Control.) | .gif) | LoadControlState | Restaure des informations sur l'état du contrôle à partir d'une demande de page antérieure enregistrée par la méthode SaveControlState. (Hérité de Control.) | .gif) | LoadViewState | Restaure les informations d'état d'affichage à partir d'une précédente requête enregistrées avec la méthode SaveViewState. (Hérité de WebControl.) | .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) | 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 s'il faut passer un événement en haut de la hiérarchie des contrôles serveur ASP.NET de la page. (Substitue Control..::.OnBubbleEvent(Object, EventArgs).) | .gif) | OnDataBinding | Déclenche l'événement DataBinding. (Hérité de Control.) | .gif) | OnInit | Déclenche l'événement Init. (Hérité de Control.) | .gif) | OnLoad | Déclenche l'événement Load. (Hérité de Control.) | .gif) | OnPreRender | Déclenche l'événement PreRender. (Hérité de Control.) | .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) | RaiseBubbleEvent | Assigne les sources éventuelles de l'événement et ses informations au parent du contrôle. (Hérité de Control.) | .gif) | RemovedControl | Appelée après la suppression d'un contrôle enfant dans la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | Render | Génère le rendu du contrôle via le writer HTML spécifié. (Hérité de WebControl.) | .gif) | RenderBeginTag | Génère le rendu de la balise d'ouverture HTML du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | RenderChildren | Renvoie le contenu des enfants d'un contrôle serveur dans un objet HtmlTextWriter fourni, qui écrit le contenu à rendre sur le client. (Hérité de Control.) | .gif) | RenderContents | Génère le rendu du contenu du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | RenderControl(HtmlTextWriter) | Renvoie le contenu du contrôle serveur dans un objet HtmlTextWriter fourni et stocke des informations de traçage au sujet du contrôle si le traçage est activé. (Hérité de Control.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Génère le contenu du contrôle serveur dans un objet HtmlTextWriter à l'aide d'un objet ControlAdapter fourni. (Hérité de Control.) | .gif) | RenderEndTag | Génère le rendu de la balise de fermeture HTML du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | ResolveAdapter | Obtient l'adaptateur de contrôles responsable du rendu du contrôle spécifié. (Hérité de Control.) | .gif) | ResolveClientUrl | Obtient une URL qui peut être utilisée par le navigateur. (Hérité de Control.) | .gif) | ResolveUrl | Convertit une URL en une URL que le client soit en mesure d'utiliser. (Hérité de Control.) | .gif) | SaveControlState | Enregistre les modifications éventuellement apportées à l'état du contrôle serveur depuis la publication de la page sur le serveur. (Hérité de Control.) | .gif) | SaveViewState | Enregistre les états modifiés après l'appel de la méthode TrackViewState. (Hérité de WebControl.) | .gif) | SetDesignModeState | Définit les données au moment du design pour un contrôle. (Hérité de Control.) | .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) | ToString | Retourne une chaîne qui représente l'objet actuel. (Hérité de Object.) | .gif) | TrackViewState | Amène le contrôle à suivre les modifications apportées à son état d'affichage afin qu'elles puissent être stockées dans la propriété ViewState de l'objet. (Hérité de WebControl.) | Début

Méthodes d'extension

Implémentations d'interface explicite
|
| Nom | Description |
|---|
.gif) .gif) | IAttributeAccessor..::.GetAttribute | Infrastructure. Obtient un attribut du contrôle Web avec le nom spécifié. (Hérité de WebControl.) | .gif) .gif) | IAttributeAccessor..::.SetAttribute | Affecte au nom et à la valeur spécifiés un attribut du contrôle Web. (Hérité de WebControl.) | .gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | Pour obtenir une description de ce membre, consultez IControlBuilderAccessor..::.ControlBuilder. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.GetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetOwnerControl. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.UserData. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.DataBindings. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.HasDataBindings. (Hérité de Control.) | .gif) .gif) | IDataItemContainer..::.DataItem | Infrastructure. Pour obtenir une description de ce membre, consultez DataItem. | .gif) .gif) | IDataItemContainer..::.DataItemIndex | Infrastructure. Pour obtenir une description de ce membre, consultez DataItemIndex. | .gif) .gif) | IDataItemContainer..::.DisplayIndex | Infrastructure. Pour une description de ce membre, consultez DisplayIndex. | .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) | IParserAccessor..::.AddParsedSubObject | Pour obtenir une description de ce membre, consultez IParserAccessor..::.AddParsedSubObject. (Hérité de Control.) | Début

Notes
La classe GridViewRow est utilisée pour représenter une ligne individuelle dans un contrôle GridView. Chaque ligne du contrôle GridView possède un type de ligne désigné. Le tableau suivant affiche les différents types de lignes. Type de ligne | Description |
|---|
DataControlRowType..::.DataRow | Ligne de données dans le contrôle GridView. | DataControlRowType..::.EmptyDataRow | Ligne vide dans le contrôle GridView. La ligne de données vide est affichée lorsque le contrôle GridView ne contient pas d'enregistrement à afficher et que le modèle GridView..::.EmptyDataTemplate n'a pas la valeur nullNothingnullptrune référence null (Nothing en Visual Basic). | DataControlRowType..::.Footer | Ligne de pied de page dans le contrôle GridView. | DataControlRowType..::.Header | Ligne d'en-tête dans le contrôle GridView. | DataControlRowType..::.Pager | Ligne de pagineur dans le contrôle GridView. | DataControlRowType..::.Separator | Ligne de séparateur dans le contrôle GridView. |
Pour déterminer le type de ligne d'un objet GridViewRow, utilisez la propriété RowType. Un état est également associé à l'objet GridViewRow. L'état peut être une combinaison d'opérations de bits des valeurs dans le tableau suivant. Valeur d'état | Description |
|---|
DataControlRowState..::.Alternate | L'objet GridViewRow est une ligne en alternance dans le contrôle GridView. | DataControlRowState..::.Edit | L'objet GridViewRow est en mode édition. | DataControlRowState..::.Normal | L'objet GridViewRow est dans son état normal (par défaut). | DataControlRowState..::.Selected | L'objet GridViewRow est sélectionné. |
Pour déterminer le type de ligne d'un objet GridViewRow, utilisez la propriété RowState. Le contrôle GridView stocke toutes ses lignes de données dans la collection Rows. Pour déterminer l'index d'un objet GridViewRow dans la collection Rows, utilisez la propriété RowIndex. Vous pouvez accéder aux propriétés de l'objet de données sous-jacent lié à l'objet GridViewRow à l'aide de la propriété DataItem. Pour déterminer l'index de l'objet de données dans la source de données sous-jacente, utilisez la propriété DataItemIndex. Vous pouvez accéder aux cellules individuelles de l'objet GridViewRow à l'aide de la propriété Cells. Si une cellule contient d'autres contrôles, vous pouvez récupérer un contrôle de celle-ci à l'aide de la collection Controls de la cellule. Vous pouvez aussi utiliser la méthode FindControl de la cellule pour rechercher le contrôle, si celui-ci possède un ID spécifié. Pour récupérer une valeur de champ à partir d'une colonne de champ BoundField ou d'une colonne de champ générée automatiquement, utilisez la propriété Text de la cellule. Pour récupérer une valeur de champ à partir des autres types de colonnes du champ où la valeur de champ est liée à un contrôle, récupérez d'abord le contrôle de la cellule voulue, puis accédez à la propriété appropriée du contrôle. Remarque |
|---|
Il est possible d'utiliser directement une expression de liaison de données dans une colonne de champ TemplateField sans lier la valeur à une propriété d'un contrôle. Dans ce cas, la valeur de champ est automatiquement placée dans un contrôle DataBoundLiteralControl. Pour récupérer la valeur de champ, vous devez d'abord récupérer le contrôle DataBoundLiteralControl de la cellule appropriée, puis utiliser sa propriété Text. |
Pour obtenir la liste des valeurs de propriétés initiales d'une instance de GridViewRow, consultez le constructeur GridViewRow.

Exemples
L'exemple suivant montre comment utiliser un objet GridViewRow pour récupérer une valeur de champ d'une cellule dans le contrôle GridView et l'afficher sur la page.
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub AuthorsGridView_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
' Get the selected row from the GridView control.
Dim selectRow As GridViewRow = AuthorsGridView.SelectedRow
' Get the author's first and last name from the appropriate
' cells in the selected row. For BoundField field columns
' and automatically generated field columns, the Text property
' of a cell is used to access a field value.
Dim lastName As String = selectRow.Cells(1).Text
' In a TemplateField column where a data-binding expression
' is used directly in the ItemTemplate, the field value
' is automatically placed in DataBoundLiteral control.
' Retrieve the DataBoundLiteral control from the cell. The
' DataBoundLiteral control is the first control in the
' Controls collection.
Dim firstNameLiteral As DataBoundLiteralControl = CType(selectRow.Cells(2).Controls(0), DataBoundLiteralControl)
Dim firstName As String = firstNameLiteral.Text
' Display the name of the selected author.
Message.Text = "You selected " & firstName & " " & lastName & "."
End Sub
</script>
<html >
<head runat="server">
<title>GridViewRow Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridViewRow Example</h3>
<asp:label id="Message"
forecolor="Red"
runat="server"/>
<br/>
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateselectbutton="true"
onselectedindexchanged="AuthorsGridView_SelectedIndexChanged"
runat="server">
<columns>
<asp:boundfield datafield="au_lname"
headertext="Last Name"/>
<asp:templatefield headertext="FirstName">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_lname], [au_fname], [address], [city], [state], [zip], [contract] FROM [authors]"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void AuthorsGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the selected row from the GridView control.
GridViewRow selectRow = AuthorsGridView.SelectedRow;
// Get the author's first and last name from the appropriate
// cells in the selected row. For BoundField field columns
// and automatically generated field columns, the Text property
// of a cell is used to access a field value.
String lastName = selectRow.Cells[1].Text;
// In a TemplateField column where a data-binding expression
// is used directly in the ItemTemplate, the field value
// is automatically placed in DataBoundLiteral control.
// Retrieve the DataBoundLiteral control from the cell. The
// DataBoundLiteral control is the first control in the
// Controls collection.
DataBoundLiteralControl firstNameLiteral = (DataBoundLiteralControl)selectRow.Cells[2].Controls[0];
String firstName = firstNameLiteral.Text;
// Display the name of the selected author.
Message.Text = "You selected " + firstName + " " + lastName + ".";
}
</script>
<html >
<head runat="server">
<title>GridViewRow Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridViewRow Example</h3>
<asp:label id="Message"
forecolor="Red"
runat="server"/>
<br/>
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateselectbutton="true"
onselectedindexchanged="AuthorsGridView_SelectedIndexChanged"
runat="server">
<columns>
<asp:boundfield datafield="au_lname"
headertext="Last Name"/>
<asp:templatefield headertext="FirstName">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_lname], [au_fname], [address], [city], [state], [zip], [contract] FROM [authors]"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
L'exemple suivant montre comment utiliser un objet GridViewRow pour récupérer un contrôle TextBox déclaré dans le modèle de modification d'élément d'une colonne de champ TemplateField. Le contrôle SqlDataSource est ensuite affecté à la zone de texte pour effectuer la mise à jour dans la source de données. Note de sécurité |
|---|
Cet exemple a une zone de texte qui accepte l'entrée d'utilisateur, ce qui constitue une menace éventuelle pour la sécurité. Par défaut, les pages Web ASP.NET vérifient que l'entrée d'utilisateur n'inclut pas de script ni d'éléments HTML. Pour plus d'informations, consultez Vue d'ensemble des attaques de script. |
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub AuthorsGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
' In this example, the GridView control will not automatically extract
' updated values from TemplateField column fields because they are not
' using a two-way binding expression. So, the updated
' values must be added manually to the NewValues dictionary.
' Get the GridViewRow object that represents the row being edited
' from the Rows collection of the GridView control.
Dim index As Integer = AuthorsGridView.EditIndex
Dim row As GridViewRow = AuthorsGridView.Rows(index)
' Get the controls that contain the updated values. In this
' example, the updated values are contained in the TextBox
' controls declared in the EditItemTemplates of the TemplateField
' column fields in the GridView control.
Dim lastName As TextBox = CType(row.FindControl("LastNameTextBox"), TextBox)
Dim firstName As TextBox = CType(row.FindControl("FirstNameTextBox"), TextBox)
' Add the updated values to the NewValues dictionary. Use the
' parameter names declared in the parameterized update query
' string for the key names.
e.NewValues("au_lname") = lastName.Text
e.NewValues("au_fname") = firstName.Text
End Sub
</script>
<html >
<head runat="server">
<title>GridViewRow Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridViewRow Example</h3>
<!-- The GridView control automatically sets the columns -->
<!-- specified in the datakeynames attribute as read-only -->
<!-- No input controls are rendered for these columns in -->
<!-- edit mode. -->
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
datakeynames="au_id"
cellpadding="10"
onrowupdating="AuthorsGridView_RowUpdating"
runat="server">
<columns>
<asp:boundfield datafield="au_id"
headertext="Author ID"
readonly="true"/>
<asp:templatefield headertext="Last Name"
itemstyle-verticalalign="Top">
<itemtemplate>
<%#Eval("au_lname")%>
</itemtemplate>
<edititemtemplate>
<asp:textbox id="LastNameTextBox"
text='<%#Eval("au_lname")%>'
width="90"
runat="server"/>
<br/>
<asp:requiredfieldvalidator id="LastNameRequiredValidator"
controltovalidate="LastNameTextBox"
display="Dynamic"
text="Please enter a last name."
runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:templatefield headertext="First Name"
itemstyle-verticalalign="Top">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
<edititemtemplate>
<asp:textbox id="FirstNameTextBox"
text='<%#Eval("au_fname")%>'
width="90"
runat="server"/>
<br/>
<asp:requiredfieldvalidator id="FirstNameRequiredValidator"
controltovalidate="FirstNameTextBox"
display="Dynamic"
text="Please enter a first name."
runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:checkboxfield datafield="contract"
headertext="Contract"
readonly="true"/>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_id], [au_lname], [au_fname], [contract] FROM [authors]"
updatecommand="UPDATE authors SET au_lname=@au_lname, au_fname=@au_fname WHERE (authors.au_id = @au_id)"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void AuthorsGridView_RowUpdating (Object sender, GridViewUpdateEventArgs e)
{
// In this example, the GridView control will not automatically extract
// updated values from TemplateField column fields because they are not
// using a two-way binding expression. So, the updated
// values must be added manually to the NewValues dictionary.
// Get the GridViewRow object that represents the row being edited
// from the Rows collection of the GridView control.
int index = AuthorsGridView.EditIndex;
GridViewRow row = AuthorsGridView.Rows[index];
// Get the controls that contain the updated values. In this
// example, the updated values are contained in the TextBox
// controls declared in the EditItemTemplates of the TemplateField
// column fields in the GridView control.
TextBox lastName = (TextBox)row.FindControl("LastNameTextBox");
TextBox firstName = (TextBox)row.FindControl("FirstNameTextBox");
// Add the updated values to the NewValues dictionary. Use the
// parameter names declared in the parameterized update query
// string for the key names.
e.NewValues["au_lname"] = lastName.Text;
e.NewValues["au_fname"] = firstName.Text;
}
</script>
<html >
<head runat="server">
<title>GridViewRow Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridViewRow Example</h3>
<!-- The GridView control automatically sets the columns -->
<!-- specified in the datakeynames attribute as read-only -->
<!-- No input controls are rendered for these columns in -->
<!-- edit mode. -->
<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
datakeynames="au_id"
cellpadding="10"
onrowupdating="AuthorsGridView_RowUpdating"
runat="server">
<columns>
<asp:boundfield datafield="au_id"
headertext="Author ID"
readonly="true"/>
<asp:templatefield headertext="Last Name"
itemstyle-verticalalign="Top">
<itemtemplate>
<%#Eval("au_lname")%>
</itemtemplate>
<edititemtemplate>
<asp:textbox id="LastNameTextBox"
text='<%#Eval("au_lname")%>'
width="90"
runat="server"/>
<br/>
<asp:requiredfieldvalidator id="LastNameRequiredValidator"
controltovalidate="LastNameTextBox"
display="Dynamic"
text="Please enter a last name."
runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:templatefield headertext="First Name"
itemstyle-verticalalign="Top">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
<edititemtemplate>
<asp:textbox id="FirstNameTextBox"
text='<%#Eval("au_fname")%>'
width="90"
runat="server"/>
<br/>
<asp:requiredfieldvalidator id="FirstNameRequiredValidator"
controltovalidate="FirstNameTextBox"
display="Dynamic"
text="Please enter a first name."
runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:checkboxfield datafield="contract"
headertext="Contract"
readonly="true"/>
</columns>
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_id], [au_lname], [au_fname], [contract] FROM [authors]"
updatecommand="UPDATE authors SET au_lname=@au_lname, au_fname=@au_fname WHERE (authors.au_id = @au_id)"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>

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
|