System.Web.UI.WebControls Namespace DataGrid Class
Sets or retrieves the index of the item to edit in a DataGrid control.
Script |
DataGrid.EditItemIndex [ = intIndex ] |
This property can only be used programmatically; it cannot be set when declaring the control.
intIndex |
Integer specifying the ordinal index of the item to edit. |
The property is read/write with no default value.
Exception Type |
Condition |
ArgumentOutOfRangeException |
The given index is set to less than -1 or greater than or equal to the items count of the list. |
Items in a DataGrid are indexed in the order in which they are defined in the data source, starting with an index of zero.
The EditItemIndex property is mainly used to programmatically specify or determine the index of the item to edit in a DataGrid. This index can then be used to access the methods and properties of the item.
EditItemIndex returns a value of -1 if no item is in edit mode. Always provide code to test this value before attempting to reference any item selected for editing in your code. You can programmatically deselect an item in edit mode by setting the EditItemIndex property to -1.
NOTE: Like most indexes in ASP.NET, EditItemIndex is zero-based, meaning the first item in the collection returns an index of 0.
The below snippet shows using EditItemIndex in the methods for handling the EditCommand, UpdateCommand and CancelCommand events, to determine the item to edit in a DataGrid control, and to reset edit mode off after the user updates or cancels the edit.
void myGridEditHandler ( Object src, DataGridCommandEventArgs e ) {
myGrid.EditItemIndex = e.Item.ItemIndex;
PopulateGrid ( );
}
void myGridUpdateHandler ( Object src, DataGridCommandEventArgs e ) {
// ... code to update data source here ...
myGrid.EditItemIndex = -1;
PopulateGrid ( );
}
void myGridCancelHandler ( Object src, DataGridCommandEventArgs e ) {
myGrid.EditItemIndex = -1;
PopulateGrid ( );
}
Sub myGridEditHandler ( src As Object, e As DataGridCommandEventArgs )
myGrid.EditItemIndex = e.Item.ItemIndex
PopulateGrid ( )
End Sub
Sub myGridUpdateHandler ( src As Object, e As DataGridCommandEventArgs )
' ... code to update data source here ...
myGrid.EditItemIndex = - 1
PopulateGrid ( )
End Sub
Sub myGridCancelHandler ( src As Object, e As DataGridCommandEventArgs )
myGrid.EditItemIndex = - 1
PopulateGrid ( )
End Sub |
|
C# |
VB |
The following examples demonstrate using the EditItemIndex property to set the index of the item to edit in a DataGrid control.
DataGrid Members EditCommandColumn EditItemStyle Allowing Users to Edit Items in a DataGrid Control