This is a migrated thread and some comments may be shown as answers.

[Solved] ExcelLike RadGrid Getting Index Out of Range Error

1 Answer 278 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Rick
Top achievements
Rank 1
Rick asked on 06 May 2013, 02:47 PM
Hi Telerik Users!

I am developing a Web Application to keep to track of inventory movements.  The Receiving Manager needs an Excel like interface.
(Got the ExcelLikeGrid code from:  http://www.telerik.com/community/code-library/aspnet-ajax/grid/excel-like-radgrid.aspx)

Currently, I have an issue that have been pondering for days and I am just not sure what could be generating the error.

I am using OpenAccess (great tool), to make the DB call to populate the radGrid.    (One thing I tried, was comment out the OpenAccess part and use a sqladapter like I have in the past, but I get the same error.

Moreover, I can step through the code and see that the first iteration of the Grid control executes with no issues.   Soon as it tries to cast the next grid item, it generates the error.  The data looks okay to me upon close examination.  I do notice that when in debug mode, that the item
control collection has a count of 0.  So, I know this is related but not sure why.  Could the underlying data be the culprit? Again, it looks good to me.  Anyway, what follows is my environment,  code, and error specifics. 

Thanks for taking a look.  If you need any futher info...let me know.

Windows 7
Visual Studio 2010
Telerik- RadControls AJAX Q3 2012 SP1
Telerik - Open Access
ASP .net 4 (VB)




BMAdmin.aspx
============================================================================
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="BMAdminHome.aspx.vb" Inherits="BINMGMT.BinAdminHome" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%@ Register assembly="Telerik.OpenAccess.Web" namespace="Telerik.OpenAccess" tagprefix="telerik" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
     <TITLE>BIN MGMT- MASTER SPAS BIN MANAGEMENT FOR RECEIVING SYSTEM</TITLE>
     <link href="Styles/bin.css" rel="stylesheet" type="text/css" />
     <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
     <script type="text/javascript">
        var radGridId = "<%=radGridMaterialLocations.ClientID %>";
    </script>
  </telerik:RadCodeBlock>
  <script src="scripts/excelOperations.js" type="text/javascript"></script>
</head>
<body class="pcBody">
    <form id="form1" runat="server">
    <!-- SQL DATA SOURCES   ------------------------------------------------------------------------------------------------>
 
    <!-- TELERIK CONTROLS   ------------------------------------------------------------------------------------------------>
 
    <telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" />
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
    <Scripts>
      <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
      <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
      <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
    </Scripts>
    </telerik:RadScriptManager>
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="radGridMaterialLocations">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="radGridMaterialLocations" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <telerik:RadNotification ID="RadNotSystemMsg" runat="server"
        CssClass="RadNotificationMsg"
        TitleIcon="Deny"      
        Position="Center"
        AutoCloseDelay="3300"
        Width="500"
        EnableRoundedCorners="true">
    </telerik:RadNotification
    <div class="binAdminHomeDiv">
         <asp:Label ID="Label1" runat="server" ForeColor="Black" CssClass="lblText" Text="[ BIN ADMIN ]" />
         <hr class="hrClass"/>
    </div>
    <div class="binAdminMLDiv">
        <asp:Label ID="Label2" runat="server" ForeColor="Black" CssClass="lblText" Text="MATERIAL LOCATIONS" />
        <telerik:RadGrid ID="radGridMaterialLocations"
            OnPreRender="radGridMaterialLocations_PreRender"
            OnDataBinding="radGridMaterialLocations_DataBinding"
            OnNeedDataSource="radGridMaterialLocations_NeedDataSource"
            OnItemCommand="radGridMaterialLocations_ItemCommand"
            runat="server" GridLines="None">
             
            <MasterTableView EditMode="InPlace" CommandItemDisplay="Top" AutoGenerateColumns="true">
                <CommandItemTemplate>
                        <asp:LinkButton ID="btnAddNew" runat="server" CommandName="AddNewRow">
                            <img style="border:0px;vertical-align:middle;" alt="" src="Images/AddRecord.gif" />Add New Row</asp:LinkButton>  
                        <asp:LinkButton ID="btnSave" runat="server" CommandName="Save">
                            <img style="border:0px;vertical-align:middle;" alt="" src="Images/save.png" />Save in Database</asp:LinkButton>  
                </CommandItemTemplate>
            </MasterTableView>
            <ClientSettings>
                <Scrolling AllowScroll="true" ScrollHeight="300" UseStaticHeaders="true" />
            </ClientSettings>
        </telerik:RadGrid>
 
    </div>
    <div class ="binAdminPMDiv">
        <asp:Label ID="Label3" runat="server" ForeColor="Black" CssClass="lblText" Text="CURRENT MOVEMENTS" />
        <br />
        <telerik:RadGrid ID="radGridPartMoves" runat="server" Width="301px" Height="500px" CellSpacing="0"
             GridLines="None" HeaderStyle-CssClass="partMoves">
            <ClientSettings>
                <Scrolling AllowScroll="True"  UseStaticHeaders="True" />
            </ClientSettings>
        </telerik:RadGrid>
        <br />
    </div>
    </form>
     
</body>
</html>
 
 
 
BMAdmin.aspx.vb
============================================================================
Imports Telerik.Web.UI
Imports System.Data
Imports System.Data.SqlClient
 
Public Class BinAdminHome
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        '// Get Part Movements...
        Dim dbContext As New BINMgmtEntities
        Dim selectedMatLoc As New SPROC_BM_MaterialLocations_SelectManagerResultSet0
        Dim IEpartMoves As IEnumerable
 
        Try
            IEpartMoves = dbContext.GetPartMovesByStocker("ALL", "None")
            radGridPartMoves.DataSource = IEpartMoves
            radGridPartMoves.DataBind()
            dbContext.Dispose()
        Catch ex As Exception
            RadNotSystemMsg.Text = "An Error Has Generated... " & ex.Message & ex.StackTrace
            'RadNotSystemMsg.Title= "--- SYSTEM ERROR ---"
            RadNotSystemMsg.TitleIcon = "Deny"
            RadNotSystemMsg.AutoCloseDelay = 0
            RadNotSystemMsg.Show()
            Err.Clear()
        Finally
 
        End Try
 
    End Sub
 
 
    'Public Property NewRowsCount() As Integer
    '    Get
    '        If Session("key") IsNot Nothing Then
    '            Return Convert.ToInt32(Session("key").ToString())
    '        Else
    '            Session("key") = 0
    '            Return 0
    '        End If
    '    End Get
    '    Set(ByVal value As Integer)
    '        Session("key") = value
    '    End Set
    'End Property
 
    'Private ReadOnly Property GridSource() As DataTable
    '    Get
    '        Dim obj As [Object] = Session(GRID_SOURCE_SESSION_KEY)
    '        If obj IsNot Nothing Then
    '            Return DirectCast(obj, DataTable)
    '        Else
    '            Dim table As New DataTable()
    '            Using conn As New SqlConnection(ConnectionString)
    '                Dim adapter As New SqlDataAdapter()
    '                adapter.SelectCommand = New SqlCommand(SELECT_QUERY, conn)
    '                conn.Open()
    '                adapter.Fill(table)
    '            End Using
    '            Session(GRID_SOURCE_SESSION_KEY) = table
    '            Return table
    '        End If
    '    End Get
    'End Property
 
    Protected Sub radGridMaterialLocations_NeedDataSource(ByVal source As Object, ByVal e As GridNeedDataSourceEventArgs)
        Dim dbContext As New BINMgmtEntities
        Dim IEmaterialLocations As IEnumerable
 
        Try
            IEmaterialLocations = dbContext.GetMaterialLocations("ALL", "None", "None", 0)
            radGridMaterialLocations.DataSource = IEmaterialLocations
 
 
            'Dim dtWarranty As New DataTable
 
            'Try
 
            '    Using SpaAdapter As New SqlDataAdapter("SPROC_BM_MaterialLocations_SelectManager", ConfigurationManager.ConnectionStrings(1).ConnectionString)
            '        SpaAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
            '        SpaAdapter.SelectCommand.Parameters.Add("@opCode", SqlDbType.VarChar).Value = "ALL"
            '        SpaAdapter.SelectCommand.Parameters.Add("@partNumber", SqlDbType.VarChar).Value = "None"
            '        SpaAdapter.SelectCommand.Parameters.Add("@vendorNumber", SqlDbType.VarChar).Value = "None"
            '        SpaAdapter.SelectCommand.Parameters.Add("@selectedID", SqlDbType.Int).Value = 0
            '        SpaAdapter.Fill(dtWarranty)
 
            '    End Using
 
            'radGridMaterialLocations.DataSource = dtWarranty
            'radGridMaterialLocations.DataBind()
 
 
 
        Catch ex As Exception
            RadNotSystemMsg.Text = "An Error Has Generated... " & ex.Message & ex.StackTrace
            'RadNotSystemMsg.Title= "--- SYSTEM ERROR ---"
            RadNotSystemMsg.TitleIcon = "Deny"
            RadNotSystemMsg.AutoCloseDelay = 0
            RadNotSystemMsg.Show()
            Err.Clear()
        Finally
 
        End Try
 
 
    End Sub
 
 
    ' Update database with the recors from the DataTable
    'Private Sub UpdateDatabase()
    '    Using conn As New SqlConnection(ConnectionString)
    '        Dim cmd As New SqlCommand(UPDATE_QUERY, conn)
    '        conn.Open()
 
    '        cmd.Parameters.Add("@EmployeeID", SqlDbType.Int)
    '        cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 20, "LastName")
    '        cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 10, "FirstName")
    '        cmd.Parameters.Add("@Title", SqlDbType.NVarChar, 30, "Title")
    '        cmd.Parameters.Add("@TitleOfCourtesy", SqlDbType.NVarChar, 25, "TitleOfCourtesy")
    '        cmd.Parameters.Add("@Address", SqlDbType.NVarChar, 60, "Address")
    '        cmd.Parameters.Add("@City", SqlDbType.NVarChar, 15, "City")
    '        cmd.Parameters.Add("@Region", SqlDbType.NVarChar, 15, "Region")
    '        cmd.Parameters.Add("@PostalCode", SqlDbType.NVarChar, 10, "PostalCode")
    '        cmd.Parameters.Add("@PhotoPath", SqlDbType.NVarChar, 255, "PhotoPath")
    '        cmd.Parameters.Add("@Country", SqlDbType.NVarChar, 15, "Country")
 
    '        For i As Integer = 0 To GridSource.Rows.Count - 1
    '            Dim grEmpRow As DataRow = GridSource.Rows(i)
    '            cmd.Parameters("@EmployeeID").Value = Convert.ToInt32(grEmpRow("EmployeeID"))
    '            cmd.Parameters("@LastName").Value = grEmpRow("LastName")
    '            cmd.Parameters("@FirstName").Value = grEmpRow("FirstName")
    '            cmd.Parameters("@Title").Value = grEmpRow("Title")
    '            cmd.Parameters("@TitleOfCourtesy").Value = grEmpRow("TitleOfCourtesy")
    '            cmd.Parameters("@Address").Value = grEmpRow("Address")
    '            cmd.Parameters("@City").Value = grEmpRow("City")
    '            cmd.Parameters("@Region").Value = grEmpRow("Region")
    '            cmd.Parameters("@PostalCode").Value = grEmpRow("PostalCode")
    '            cmd.Parameters("@PhotoPath").Value = grEmpRow("PhotoPath")
    '            cmd.Parameters("@Country").Value = grEmpRow("Country")
 
    '            cmd.ExecuteScalar()
    '        Next
    '    End Using
    'End Sub
 
    ' Add all new rows from DataTable into Database
    'Private Sub AddNewRowsInDatabase()
    '    Dim conn As New SqlConnection(ConnectionString)
 
    '    If NewRowsCount > 0 Then
    '        Using cmdInsert As New SqlCommand(INSERT_QUERY, conn)
    '            conn.Open()
    '            For i As Integer = 0 To NewRowsCount - 1
    '                cmdInsert.ExecuteScalar()
    '            Next
    '        End Using
    '    End If
    'End Sub
 
    ' Add new empty row into DataTable
    'Private Sub AddNewRowInDataTable()
    '    Dim id As Integer = Convert.ToInt32(GridSource.Rows(GridSource.Rows.Count - 1)("EmployeeID").ToString())
    '    NewRowsCount += 1
    '    Dim row As DataRow = GridSource.NewRow()
    '    row("EmployeeID") = id + 1
    '    row("LastName") = ""
    '    row("Title") = ""
    '    row("TitleOfCourtesy") = ""
    '    row("Address") = ""
    '    row("City") = ""
    '    row("Region") = ""
    '    row("PostalCode") = ""
    '    row("PhotoPath") = ""
    '    row("Country") = ""
    '    GridSource.Rows.Add(row)
    '    radGridMaterialLocations.Rebind()
    'End Sub
 
    '' Get data from the RadGrid and save it into the DataTable
    'Private Sub saveDataInDataTable()
    '    For i As Integer = 0 To radGridMaterialLocations.MasterTableView.Items.Count - 1
    '        Dim item As GridDataItem = radGridMaterialLocations.MasterTableView.Items(i)
    '        Dim idColumn As GridColumn = radGridMaterialLocations.MasterTableView.RenderColumns(2)
    '        Dim id As Integer = Convert.ToInt32(TryCast(item(idColumn.UniqueName).Controls(0), RadNumericTextBox).Text)
 
    '        Dim myDataRow As DataRow = GridSource.Rows(i)
    '        myDataRow("LastName") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(3).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("FirstName") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(4).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("Title") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(5).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("TitleOfCourtesy") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(6).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("Address") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(7).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("City") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(8).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("Region") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(9).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("PostalCode") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(10).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("PhotoPath") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(11).UniqueName).Controls(0), TextBox).Text
    '        myDataRow("Country") = TryCast(item(radGridMaterialLocations.MasterTableView.RenderColumns(12).UniqueName).Controls(0), TextBox).Text
    '    Next
    'End Sub
 
 
 
    Protected Sub radGridMaterialLocations_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
        For i As Integer = 0 To radGridMaterialLocations.Items.Count
            radGridMaterialLocations.EditIndexes.Add(i)
        Next
    End Sub
 
    Protected Sub radGridMaterialLocations_PreRender(ByVal sender As Object, ByVal e As EventArgs)
        radGridMaterialLocations.Attributes.Add("onkeydown", "onKeyDown(this,event);")
        Dim itemsCount As Integer = 0
        Dim columnsCount As Integer = 0
        Dim builder As New StringBuilder()
 
 
        ' Attach the event handlers to the client side events of the TextBoxes.
 
        For Each item As GridDataItem In radGridMaterialLocations.MasterTableView.Items
            If TypeOf item Is GridDataItem Then
                columnsCount = 0
                For i As Integer = 2 To radGridMaterialLocations.MasterTableView.RenderColumns.Length - 1
                    Dim column As GridColumn = radGridMaterialLocations.MasterTableView.RenderColumns(i)
 
                    If column.UniqueName = "MaterialLocationID" Then
                        Dim radNumericTextBox As RadNumericTextBox = TryCast(item(column.UniqueName).Controls(0), RadNumericTextBox)
                        If radNumericTextBox IsNot Nothing Then
                            radNumericTextBox.Enabled = False
                            radNumericTextBox.Attributes.Add("class", "readOnly")
                        End If
                        Dim textBox As TextBox = TryCast(item(column.UniqueName).Controls(0), TextBox)
                        If textBox IsNot Nothing Then
                            textBox.[ReadOnly] = True
                            textBox.Attributes.Add("class", "readOnly")
                        End If
                    Else
                        Dim textBox As TextBox = TryCast(item(column.UniqueName).Controls(0), TextBox)
                        If textBox IsNot Nothing Then
                            textBox.Attributes.Add("ondblclick", "cellDoubleClickFunction('" + textBox.ClientID & "');")
                            textBox.Attributes.Add("onclick", "cellClick('" + textBox.ClientID & "');")
 
                        End If
                    End If
                    columnsCount += 1
                Next
                itemsCount += 1
            End If
        Next
        RadScriptManager.RegisterStartupScript(Page, Page.[GetType](), "init", "colls = " & columnsCount & ";rows=" & itemsCount & ";", True)
    End Sub
 
 
    Protected Sub radGridMaterialLocations_ItemCommand(ByVal source As Object, ByVal e As GridCommandEventArgs)
        '    saveDataInDataTable()
        '    Select Case e.CommandName
        '        Case "InsertNewRow"
        '            If True Then
        '                AddNewRowInDataTable()
 
        '                Dim script As String = "setTimeout( function () { selectedCellId='" & e.CommandArgument.ToString() & "'; MoveDown();},100);"
        '                ScriptManager.RegisterStartupScript(Page, Page.[GetType](), "selectCell", script, True)
        '                ViewState("inserted") = True
 
        '            End If
        '            Exit Select
        '        Case "AddNewRow"
        '            If True Then
        '                AddNewRowInDataTable()
        '            End If
        '            Exit Select
        '        Case "Save"
        '            If True Then
        '                saveDataInDataTable()
        '                AddNewRowsInDatabase()
        '                UpdateDatabase()
        '                RadAjaxManager1.Alert("The database was successfully updates")
        '            End If
        '            Exit Select
        '        Case Else
        '            Exit Select
        '    End Select
    End Sub
 
 
End Class



 

Server Error in '/BINMgmt' Application.

Specified argument was out of the range of valid values.
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.

Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: index

Source Error:

Line 222: Line 223: 
If column.UniqueName = "MaterialLocationID" Then
Line 224: Dim radNumericTextBox As RadNumericTextBox = TryCast(item(column.UniqueName).Controls(0), RadNumericTextBox) Line 225: If radNumericTextBox IsNot Nothing Then Line 226: radNumericTextBox.Enabled = False

Source File: C:\Projects\BIN Mgmt\BMAdminHome.aspx.vb Line: 224

Stack Trace:

[ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index] System.Web.UI.ControlCollection.get_Item(Int32 index) +11408022 BINMGMT.BinAdminHome.radGridMaterialLocations_PreRender(Object sender, EventArgs e) in C:\Projects\BIN Mgmt\BMAdminHome.aspx.vb:224 Telerik.Web.UI.RadCompositeDataBoundControl.OnPreRender(EventArgs e) +46 System.Web.UI.Control.PreRenderRecursiveInternal() +113 System.Web.UI.Control.PreRenderRecursiveInternal() +222 System.Web.UI.Control.PreRenderRecursiveInternal() +222 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4201 


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272







1 Answer, 1 is accepted

Sort by
0
Andrey
Telerik team
answered on 09 May 2013, 12:26 PM
Hello,

Most probably the problem comes from this code:

Protected Sub radGridMaterialLocations_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
        For i As Integer = 0 To radGridMaterialLocations.Items.Count
            radGridMaterialLocations.EditIndexes.Add(i)
        Next
    End Sub

At this stage the Items.Cound of RadGrid is 0, so your For loop does not put any items in edit mode and that is why the controls collection does not hold any controls.

Try to query the datasource directly for the numbers of items that RadGrid is bound to. As you could verify from the code provided in the code-library project we are using a property which holds the numbers of items that RadGrid is bound to.

All the best,
Andrey
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
Tags
Grid
Asked by
Rick
Top achievements
Rank 1
Answers by
Andrey
Telerik team
Share this question
or