none
The index was out of bounds. It must not be negative and must be smaller than the size of the collection. RRS feed

  • Question

  • Hi,

    I get this Error " The index was out of bounds. It must not be negative and must be smaller than the size of the collection."

    This is My code:

    Private Sub ShowSevragesByCage() If Not String.IsNullOrEmpty(CmbCages.Text) Then _bsc2.DataSource = opsd.NetSevragesByCage(CmbCages.Text) Dgv.DataSource = _bsc2 Dgv.ExpandColumns() End If ' Sum Dim Sum As Integer = 0 For i As Integer = 0 To Dgv.Rows.Count - 1 - 1 Sum += Convert.ToInt32(Dgv.Rows(i).Cells(4).Value) Next

         Dgv("NetDesSevrages", Dgv.Rows.Count - 1).Value = Sum

    End sub

    The problem is in the last line , whithout it the Sub run .

      Dgv("NetDesSevrages", Dgv.Rows.Count - 1).Value = Sum
    cast

    Without the last line:

    cast

    So thank you very Much.

    Best Regards.

    Monday, March 25, 2019 9:35 AM

All replies

  • Try using 

    Dim Test As Integer = Dgv.Rows.Count - 1

    Put a breakpoint on that line to see what the value of Test is.

    Also this

    For i As Integer = 0 To Dgv.Rows.Count - 1 - 1

    Should be

    For i As Integer = 0 To Dgv.Rows.Count - 1 


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, March 25, 2019 9:43 AM
    Moderator
  • Hi,

    The DataGridView1.Rows.Count - 1 line is out of bounds, but you should not get an error from your code and the image provided.Please provide your code.

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, March 25, 2019 10:32 AM
  • Try using 

    Dim Test As Integer = Dgv.Rows.Count - 1

    Put a breakpoint on that line to see what the value of Test is.

    Also this

    For i As Integer = 0 To Dgv.Rows.Count - 1 - 1

    Should be

    For i As Integer = 0 To Dgv.Rows.Count - 1 

    Hi , 

    I tested but I get no value,

    For i As Integer = 0 To Dgv.Rows.Count - 1 - 1 Or

    For i As Integer = 0 To Dgv.Rows.Count - 1 , display the same error message.

    so Thank you very Much ,

    Best regards.

    Monday, March 25, 2019 1:18 PM
  • Hi,

    The DataGridView1.Rows.Count - 1 line is out of bounds, but you should not get an error from your code and the image provided.Please provide your code.

    Best Regards,

    Alex


    Hi, 

    the code for second Image ,without the last line of code .

        Private Sub ShowSevragesByCage()
            If Not String.IsNullOrEmpty(CmbCages.Text) Then
                _bsc2.DataSource = opsd.NetSevragesByCage(CmbCages.Text)
                Dgv.DataSource = _bsc2
                Dgv.ExpandColumns()
            End If
            ' Sum
            Dim Sum As Integer = 0
            For i As Integer = 0 To Dgv.Rows.Count - 1 - 1
                Sum += Convert.ToInt32(Dgv.Rows(i).Cells(4).Value)
            Next
        End Sub

    Thank you very Much ,

    Best Regards.

    Monday, March 25, 2019 1:22 PM
  • How about this replace TextBox with the object you want to setup the sum value too.

    Public Class Form2
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 2})
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 3})
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 4})
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 3})
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 3})
    
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            TextBox1.Text = DataGridView1.
                Rows.Cast(Of DataGridViewRow).
                Where(Function(row) Not row.IsNewRow).
                Select(Function(row) CInt(row.Cells(4).Value)).
                Sum().
                ToString()
        End Sub
    End Class


    This sets the value to a new row

    Public Class Form2
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 2})
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 3})
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 4})
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 3})
            DataGridView1.Rows.Add(New Object() {"C-D45F", "Point5", 10, "aaa", 3})
    
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            DataGridView1.Rows.Add(New Object() _
                {"", "", Nothing, "",
                 DataGridView1.
                  Rows.Cast(Of DataGridViewRow).
                  Where(Function(row) Not row.IsNewRow).
                  Select(Function(row) CInt(row.Cells(4).Value)).
                  Sum().
                  ToString()})
    
        End Sub
    End Class


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, March 25, 2019 2:22 PM
    Moderator
  • This sets the value to a new row


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click DataGridView1.Rows.Add(New Object() _ {"", "", Nothing, "", DataGridView1. Rows.Cast(Of DataGridViewRow). Where(Function(row) Not row.IsNewRow). Select(Function(row) CInt(row.Cells(4).Value)). Sum(). ToString()}) End Sub End Class

    Hi, 

    I Tested the above  samples in quote and I get this Error:

    ''Can not add a row to a DataGridView control that does not have columns. The columns must be added beforehand.''

    well this is the whole code I am using :

      Public Class MainDetailsOperations
      Public Function NetSevragesByCage(ByVal MyCage As Int32) As DataTable
    
    
            Dim selectStatement As String =
                        <SQL>
             SELECT [DaTaPontes.CID] as CID, 
                    [DaTaPontes.CoupleID] as CoupleCode, 
                    [DataPontes.Pontes] as Ponte,
                    [DaTaPontes.Cage] as Cage , 
                    [DaTaPontes.Race] as Race ,
                    IIf(IsNull([DaTaPontes.NetOiseauxSevrés]),0,[DaTaPontes.NetOiseauxSevrés]) As NetDesSevrages                                 
                    FROM DaTaPontes where DaTaPontes.Cage=@Cages order by dataPontes.Cage
    
    
                    </SQL>.Value
            Using cn As New OleDb.OleDbConnection With
                    {
                        .ConnectionString = Builder.ConnectionString
                    }
                Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
                    cmd.CommandText = selectStatement
    
    
                    cmd.Parameters.Add(New OleDb.OleDbParameter With
                                       {
                                           .DbType = DbType.Int32,
                                           .ParameterName = "@Cages",
                                           .Value = MyCage
                                       }
                                   )
    
                    Dim dt As New DataTable
    
                    cn.Open()
                    dt.Load(cmd.ExecuteReader)
                    dt.Columns("CID").ColumnMapping = MappingType.Hidden
    
                    Return dt
                End Using
            End Using
        End Function 
           Public Function listDesCages() As List(Of Int32)
    
            Dim Lcage As New List(Of Int32)
    
            Using cn As New OleDb.OleDbConnection With
                    {
                        .ConnectionString = Builder.ConnectionString
                    }
                Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
    
                    cmd.CommandText = "SELECT Cage from DaTaPontes group by Cage"
                    cn.Open()
                    Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
    
                    If Reader.HasRows Then
    
                        While Reader.Read
                            Lcage.Add(Reader.GetInt32(0))
                        End While
                    End If
                    Reader.Close()
                    Return Lcage
                End Using
            End Using
    
           End Function
          end class
    
    '' *****
      Imports System.IO
    
      Public Class MainPontes  
      Dim Ops As New MainDetailsOperations
      Dim _bs1 as New BindingSource
      Dim _bs2 as New BindingSource
        Private Sub MainPontes_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CmbCages.DataSource = Ops.listDesCages()
        CmbCages.SelectedIndex = -1
        end sub
    
            Private Sub CmbCages_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbCages.SelectedIndexChanged
            If Not IsNothing(_bs1) Then
                _bs1.Position = CmbCages.SelectedIndex
            End If
            ShowNetSevragesByCage()
            End Sub
            Private Sub ShowNetSevragesByCage()
            If Not String.IsNullOrEmpty(CmbCages.Text) Then
                _bs2.DataSource = Ops.NetSevragesByCage(CInt(CmbCages.Text))
                Dgv.DataSource = _bs2
                Dgv.ExpandColumns()
            End If
            dim sum as integer= 0
            ' Sum
             For i As Integer = 0 To Dgv.Rows.Count - 1 - 1
             Sum += Convert.ToInt32(Dgv.Rows(i).Cells(4).Value)
              Next
              Dgv("NetDesSevrages", Dgv.Rows.Count - 1).Value = Sum '
              Dgv.Rows(Dgv.Rows.Count - 1).DefaultCellStyle.BackColor = Color.YellowGreen
              Dgv.Rows(Dgv.Rows.Count - 1).DefaultCellStyle.ForeColor = Color.Black
              Dgv.Rows(Dgv.Rows.Count - 1).DefaultCellStyle.Font = New Font("Segoe UI", 9, (FontStyle.Bold))
        End Sub
    end class

    This is The DataBase from OneDrive :DataBase

    Thank you for you assistance .

    Best Regards.



    • Edited by Bajtitou Monday, March 25, 2019 5:13 PM
    Monday, March 25, 2019 5:08 PM
  • Hello,

    I assumed your DataGridView had columns defined after seeing

    Dgv.ExpandColumns()


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Proposed as answer by Alex Li-MSFT Thursday, March 28, 2019 7:10 AM
    Monday, March 25, 2019 6:53 PM
    Moderator