PRB: "Index Was Out of Range" Error Message from the DataGrid While Paging (813832)
The information in this article applies to:
- Microsoft ASP.NET (included with the .NET Framework) 1.0
- Microsoft Visual Basic .NET (2002)
- Microsoft Visual C# .NET (2002)
- Microsoft ASP.NET (included with the .NET Framework 1.1)
- Microsoft Visual C# .NET (2003)
- Microsoft Visual Basic .NET (2003)
SYMPTOMSTo trap the record that is being accessed in a DataGrid Web server control, you use
the DataKeys collection of DataGrid on an ItemCommand event, and then pass the ItemIndex
property as a key to the DataKey collection. When you click a link to move to the next
page (or to a new page) in the DataGrid, you may receive the following error
message: Index was out of range. Must be non-negative and
less than the size of the collection. Parameter name: index Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information about
the error and where it originated in the
code. CAUSEWhen you click a link to move to the next page (or to a new page)
in the DataGrid, the ItemCommand event is invoked. The value of the ItemIndex
property is -1 in the ItemCommand event. You may receive an error when you
pass the ItemIndex property as a key to retrieve the value from the DataKey
collection because the DataKey collection is zero bound.WORKAROUNDTo work around this problem, retrieve a value from the
DataKey collection only when the value of the ItemIndex property is greater than or equal to 0. The
following ItemCommand event sample code demonstrates how to do this. Visual C# .NET Sample Codeprivate void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// If Not navigating to Next Page, show the CategoryID in the text box.
if (e.Item.ItemIndex > -1)
{
// Get the CategoryID of the Row Selected in the DataGrid.
TextBox1.Text = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
}
}
Visual Basic .NET code Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.ItemCommand
' If Not navigating to Next Page, show the CategoryID in the text box.
If e.Item.ItemIndex > -1 Then
' Get the CategoryID of the Row Selected in the DataGrid.
TextBox1.Text = DataGrid1.DataKeys(e.Item.ItemIndex)
End If
End Sub
STATUS This
behavior is by design.REFERENCESFor more information about creating and populating a DataGrid control, visit the following Microsoft Web site: For
additional information, click the following article number to view the article
in the Microsoft Knowledge Base: 318131
HOW TO: Page Through a Query Result for Better Performance
Modification Type: | Minor | Last Reviewed: | 4/30/2003 |
---|
Keywords: | kbWebForms kbweb kberrmsg kbEvent kbDataAdapter kbDataBinding kbServerControls kbprb KB813832 kbAudDeveloper |
---|
|