GridView.EditIndex Propriedade
Definição
Obtém ou define o índice da linha para edição.Gets or sets the index of the row to edit.
public:
virtual property int EditIndex { int get(); void set(int value); };
public virtual int EditIndex { get; set; }
member this.EditIndex : int with get, set
Public Overridable Property EditIndex As Integer
Valor da propriedade
O índice baseado em zero da linha a ser editada.The zero-based index of the row to edit. O padrão é -1, que indica que nenhuma linha está sendo editada.The default is -1, which indicates that no row is being edited.
Exceções
O índice especificado é menor que -1.The specified index is less than -1.
Exemplos
O exemplo a seguir demonstra como usar a EditIndex propriedade para determinar qual linha foi atualizada depois de ser editada em um GridView controle.The following example demonstrates how to use the EditIndex property to determine which row was updated after it was edited in a GridView control. Uma mensagem é exibida para indicar que a atualização foi bem-sucedida.A message is displayed to indicate that the update was successful.
<%@ 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 CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// Clear the message label when the user enters edit mode.
if (e.CommandName == "Edit")
{
Message.Text = "";
}
}
void CustomersGridView_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
{
// The update operation was successful. Retrieve the row being edited.
int index = CustomersGridView.EditIndex;
GridViewRow row = CustomersGridView.Rows[index];
// Notify the user that the update was successful.
Message.Text = "Updated record " + row.Cells[1].Text + ".";
}
void CustomersGridView_RowCancelingEdit(Object sender, GridViewCancelEditEventArgs e)
{
// The update operation was canceled. Display the appropriate message.
Message.Text = "Update operation canceled.";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView Rows Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView Rows Example</h3>
<asp:label id="Message"
forecolor="Red"
runat="server"/>
<br/>
<!-- The GridView control automatically sets the columns -->
<!-- specified in the datakeynames property as read-only. -->
<!-- No input controls are rendered for these columns in -->
<!-- edit mode. -->
<asp:gridview id="CustomersGridView"
allowpaging="true"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="true"
autogenerateeditbutton="true"
datakeynames="CustomerID"
onrowcommand="CustomersGridView_RowCommand"
onrowupdated="CustomersGridView_RowUpdated"
onrowcancelingedit="CustomersGridView_RowCancelingEdit"
runat="server">
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="CustomersSqlDataSource"
selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
updatecommand="Update Customers SET CompanyName=@CompanyName, Address=@Address, City=@City, PostalCode=@PostalCode, Country=@Country WHERE (CustomerID = @CustomerID)"
deletecommand="Delete from Customers where CustomerID = @CustomerID"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub CustomersGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
' Clear the message label when the user enters edit mode.
If e.CommandName = "Edit" Then
Message.Text = ""
End If
End Sub
Sub CustomersGridView_RowUpdated(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs)
' The update operation was successful. Retrieve the row being edited.
Dim index As Integer = CustomersGridView.EditIndex
Dim row As GridViewRow = CustomersGridView.Rows(index)
' Notify the user that the update was successful.
Message.Text = "Updated record " & row.Cells(1).Text + "."
End Sub
Sub CustomersGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
' The update operation was canceled. Display the appropriate message.
Message.Text = "Update operation canceled."
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView Rows Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView Rows Example</h3>
<asp:label id="Message"
forecolor="Red"
runat="server"/>
<br/>
<!-- The GridView control automatically sets the columns -->
<!-- specified in the datakeynames property as read-only. -->
<!-- No input controls are rendered for these columns in -->
<!-- edit mode. -->
<asp:gridview id="CustomersGridView"
allowpaging="true"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="true"
autogenerateeditbutton="true"
datakeynames="CustomerID"
onrowcommand="CustomersGridView_RowCommand"
onrowupdated="CustomersGridView_RowUpdated"
onrowcancelingedit="CustomersGridView_RowCancelingEdit"
runat="server">
</asp:gridview>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="CustomersSqlDataSource"
selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
updatecommand="Update Customers SET CompanyName=@CompanyName, Address=@Address, City=@City, PostalCode=@PostalCode, Country=@Country WHERE (CustomerID = @CustomerID)"
deletecommand="Delete from Customers where CustomerID = @CustomerID"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server">
</asp:sqldatasource>
</form>
</body>
</html>
Comentários
O índice de linha é baseado em zero (a primeira linha é de linha zero).The row index is zero-based (the first row is row zero).
Essa propriedade normalmente é usada apenas nos seguintes cenários, que envolvem manipuladores para eventos específicos:This property is typically used only in the following scenarios, which involve handlers for specific events:
Você deseja que o GridView controle seja aberto no modo de edição para uma linha específica na primeira vez em que a página é exibida.You want the GridView control to open in edit mode for a specific row the first time that the page is displayed. Para fazer isso, você pode definir a EditIndex propriedade no manipulador para o Load evento da Page classe ou do GridView controle.To do this, you can set the EditIndex property in the handler for the Load event of the Page class or of the GridView control.
Você deseja saber qual linha foi editada após a atualização da linha.You want to know which row was edited after the row was updated. Para fazer isso, você pode recuperar o índice de linha da EditIndex propriedade no RowUpdated manipulador de eventos.To do this, you can retrieve the row index from the EditIndex property in the RowUpdated event handler.
Você está associando o GridView controle a uma fonte de dados definindo a DataSource propriedade programaticamente.You are binding the GridView control to a data source by setting the DataSource property programmatically. Nesse caso, você deve definir a EditIndex Propriedade nos RowEditing RowCancelingEdit manipuladores de eventos e.In this case you must set the EditIndex property in the RowEditing and RowCancelingEdit event handlers.
Se você definir a EditIndex propriedade após um postback ou em manipuladores para eventos que são gerados mais tarde do que o Load evento, o GridView controle pode não entrar no modo de edição para a linha especificada.If you set the EditIndex property after a postback or in handlers for events that are raised later than the Load event, the GridView control might not enter edit mode for the specified row. Se você ler o valor dessa propriedade em outros manipuladores de eventos, não haverá garantia de que o índice reflita a linha que está sendo editada.If you read the value of this property in other event handlers, the index is not guaranteed to reflect the row that is being edited.
Para determinar em qual linha o usuário clicou em um botão de edição ou hiperlink antes de o GridView controle entrar no modo de edição, você pode recuperar o índice de linha da NewEditIndex Propriedade do GridViewEditEventArgs objeto no RowEditing manipulador de eventos.To determine which row the user has clicked an Edit button or hyperlink in before the GridView control enters edit mode, you can retrieve the row index from the NewEditIndex property of the GridViewEditEventArgs object in the RowEditing event handler.
Para impedir que o GridView controle entre no modo de edição depois que um usuário clicar em um botão ou hiperlink de edição , defina a Cancel Propriedade do GridViewEditEventArgs objeto como true no RowEditing manipulador de eventos.To prevent the GridView control from entering edit mode after a user has clicked an Edit button or hyperlink, set the Cancel property of the GridViewEditEventArgs object to true in the RowEditing event handler.