Search code examples
vb.netnumericupdown

Updating Values in a Data Grid View With Key Press Data Entry in Numeric Up and Down


I am setting up a Data Grid View that contains a list of items, with one column as the Item Number (1, 2, 3) and the second number as the name of the items. I am controlling the input of the Item Number column using a Numeric Up and Down, so when I increase it, the rows are added and the Item Number column is automatically updated (so the user doesn't have to enter this in). However, this only works if I use the numeric up and down by clicking the arrows. If I type in the number (say 4 items), I get an exception (System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index') and the procedure doesn't work. The code is below:

Private Sub numItemNumber_ValueChanged(sender As Object, e As EventArgs) Handles numItemNumber.ValueChanged
     While (dgvItems.Rows.Count < numItemNumber.Value)
        dgvItems.Rows.Add()
        i = numItemNumber.Value
        dgvItems.Rows(i).Cells(0).Value = i + 1  'This is where the exception is
    End While
   End Sub

I added in a KeyPress event to see if that could handle the item entered in but it doesn't.

 Private Sub numItemNumber_KeyPress(sender As Object, e As EventArgs) Handles numItemNumber.KeyPress
    For i = 0 To numItemNumber.Value - 1
        dgvItems.Rows(i).Cells(0).Value = i + 1
    Next
End Sub

How can I edit this to include both events (the user using the up and down keys or just entering the number in directly)? Thank you.


Solution

  • Figured out this works, essentially adding a loop through the rows of the data grid view in the Value Changed event so that it can handle any number > 0. Adding the code here for anyone who possibly needs it:

    Private Sub numItemNumber_ValueChanged(sender As Object, e As EventArgs) Handles numItemNumber.ValueChanged
     While (dgvItems.Rows.Count < numItemNumber.Value)
        For i=0 to numItemNumber.Value-1
             dgvItems.Rows.Add()
             dgvItems.Rows(i).Cells(0).Value = i + 1  
        Next
      End While
    End Sub
    

    The KeyPress Event is not needed.