Index Out Of Range (Range Is Variable) - vb.net

So I'm trying to return all the column names in my datagridview. The code below returns the column names except at the end, I a message stating Index was out of range I assume this is because I have less than 500 columns in my datagridview.
The 500 could in theory be any amount, some might only have 20 columns, others might have 300 columns.
How would I go about clearing up this error?
Dim c As Integer
For cn = 0 To 500
c = c + cn
'Debug.Print(cn)
Debug.Print(DataGridView1.Columns(cn).Name)
Next cn

"Index out of range" exception can happen when you are trying to access a member of collection under index that doesn't exist
Lets take your example - you getting error here DataGridView1.Columns(cn) because your cn has a value which doesn't exist in DataGridView1.Columns. For example, if you have 2 columns, your indexes are 0 and 1. If you try to ask for DataGridView1.Columns(2) - you will get this exception. So, as mentioned above in comments, when dealing with collections you either use For Each loop or you use For... count -1 loop
This is correct code:
For i as Integer = 0 To DataGridView1.Columns.Count - 1
Debug.WriteLine(DataGridView1.Columns(i).Name)
Next
Example of For Each
For Each s as String In myStrings ' myStrings can be List(Of String)
Debug.WriteLine(s)
Next

Related

Dim n variables where n is a user defined number

I have to dim n variables in my software, where n is a number that user types in the interface. I'd start with a for loop, in order to declare these variables, with something like:
for i = 0 to n
dim r.i as IRow = worksheet.CreateRow(i)
next
This is what I think but obviously I know that's wrong. Does anyone knows if this is possible? I can't create neither List(Of) nor arrays because these are rows of an excel file I'm trying to export, otherwise NPOI returns me error.
What does Excel have anything to do with not using a List? You can absolutely use worksheet.CreateRow() with a list:
Dim rows As New List(Of IRow)
For i As Integer = 0 to n - 1
rows.Add(worksheet.CreateRow(i))
Next
Now the name of each row is row(0), row(1), row(2) ... row(n - 1)
If you've tried this and NPOI is giving you an error, you should show that code around where the error is thrown and tell us what the error is.
Based on comments:
'Assuming everything has the same number of entries as ListBox1, per the comments
Dim rows As New List(Of IRow)
Dim row As IRow = worksheet.CreateRow(0)
row.CreateCell(0).SetCellValue("Time")
row.CreateCell(1).SetCellValue("hrr")
For i As Integer = 0 To ListBox1.Items.Count - 1
row = worksheet.CreateRow(i+1)
row.CreateCell(0).SetCellValue(ListBox1.Items(i))
row.CreateCell(1).SetCellValue(ListBox2.Items(i))
rows.Add(row)
Next i

Determine if an integer is a member of a list of integers

I need to determine if a particular integer does not exists in a datagridview column. I assume I should create an array of the integers from the dgv column, and then compare if the integer exists in the array. However, there is perhaps an easier or simpler way.
I have looked at many articles but none of them resolve my task. Some of the Stack Overflow articles show similar solutions but I can't quite determine what to do.
For a = 0 To Dgv1.RowCount - 1
If Not Dgv1(1, a).Value = Dgv0(1, m).Value Then
Dgv0(1, Dgv0.RowCount - 1).Value = Dgv0(1, m).Value
End If
Next
I hope to compare an integer with a column of integers in a datagridview and if it is present do nothing but if is not present add it to the datagrid view
Are you using wpf? If yes, create a model.
provide a checking mechanism at the setter, use observablecollection or list then bind it to the datagirdview
Get the row and column of the datagridview
then compare (means condtional statement) to the variable you wanna check
and of course it should be inside of loop, loop count is equal to the count of rows you have in the datagridview.
Here's an example code:
Dim column As String = "YourColumnNameHere"
' Assuming 2 is the number you wanna compare
Dim value As Integer = 2
For row As integer = 0 to dataGridView.RowCount - 1
If dataGridView.Rows(row).Cells(column).Value = value Then
' Do something here
Else
' Do something here
End If
Next

I'm trying to sum the number of rows that are not nothing. IF the row count is 2, but LastNAme (row 2) is Nothing, i need to return 1

I'm trying to get an accurate count of borrowers on a loan. The system I'm working in automatically creates 2 rows for each application we enter. I want to return the sum of rows that are not nothing.
I'm looking at the borrower last name. So if we have two applications on the loan file, our system automatically creates 4 rows. However, the borrower last name field in row 4 is nothing. I want to return 3 since the borrower last name field in rows 1, 2 and 3 is not nothing
I'm fairly new to VB.NET and am trying to use a For Loop to count each row when the last name is not nothing.
Dim i As Integer
Dim BrwrCT = GetFieldRowCount(144)
For i = 1 To BrwrCT
If GetFieldValue(144,i) IsNot Nothing
Return 1 + BrwrCT
Else Return BrwrCT
End If
Next i
For this example, the loan file has 3 borrowers and the result should be returning 3, however, I am receiving 5 (BrwrCT + 1)
In your For/Next loop you set the max loop to be BrwrCT and then inside of the loop you are modifying the value of that same variable BrwrCT. You should avoid modifying the loop range inside of the loop doing that range. You should also not use the Return statement inside of the loop unless you actually want to leave that loop immediately without performing all of the iterations of that loop. In your sample code, this loop would only ever execute once and then immediately exit (aka Return).
I recommend creating a second variable that will have the count you are looking for:
Dim i As Integer
Dim BrwrCT = GetFieldRowCount(144)
Dim totalBorrowers As Integer
For i = 1 To BrwrCT
If GetFieldValue(144,i) IsNot Nothing Then
totalBorrowers += 1
End If
Next i
Return totalBorrowers

Remove elements in an arraylist that exist in another arraylist

i have 2 array list, dateListDead and dateListNotMinggu. Both is DateTime List of Array. This is the ilustration of the date value in list of array
The arrayList value
its supposed to remove specific element that exist in other array list.
so far i tried, this code it's not working.
Dim d, x As Integer
For x = 0 To dateListDead.Count - 1
For d = 0 To dateListNotMinggu.Count - 1
If dateListNotMinggu(d) = dateListDead(x) Then
dateListNotMinggu.RemoveAt(d)
End If
Next
Next
the error is : index out of range. how could it be ? i define the parameter of end looping base on arraylist.count -1
The main is that you are using a For loop from the first index to the last index but you don't account for the change of index when you remove a value. If there might be multiple values then you should start and the end rather than the beginning. In that case, removing an item won't affect the indexes of the items you are yet to test. If there can only be one match then you should be exiting the loop when you find one.
Either way, while you don't have to, I would suggest using a For Each loop on the outside. If you want to perform an action for each item in a list then that's exactly what a For Each loop is for. Only use a For loop if you need to use the loop counter for something other than accessing each item in turn.
For multiple matches:
For Each dateDead As Date In dateListDead
For i = dateListNotMinggu.Count - 1 To 0 Step -1
If CDate(dateListNotMinggu(i)) = dateDead Then
dateListNotMinggu.RemoveAt(i)
End If
Next
Next
For a single match:
For Each dateDead As Date In dateListDead
For i = 0 To dateListNotMinggu.Count - 1
If CDate(dateListNotMinggu(i)) = dateDead Then
dateListNotMinggu.RemoveAt(i)
Exit For
End If
Next
Next
Note that I have also cast the Date values as that type for comparison, which is required with Option Strict On. Option Strict is Off by default but you should always turn it On because it will help you write better code by focusing on data types.
Also, the code above would work with a List(Of Date) as well as an ArrayList but the casts would not be required with a List(Of Date). That's one of the advantages of using a generic List(Of T) over an ArrayList, which paces no restrictions on what it can contain.
If you really must use a For loop because that's what your homework assignment says then it would look like this:
For i = 0 To dateListDead.Count - 1
For j = dateListNotMinggu.Count - 1 To 0 Step -1
If CDate(dateListNotMinggu(j)) = CDate(dateListDead(i)) Then
dateListNotMinggu.RemoveAt(j)
End If
Next
Next
and this:
For i = 0 To dateListDead.Count - 1
For j = 0 To dateListNotMinggu.Count - 1
If CDate(dateListNotMinggu(j)) = CDate(dateListDead(i)) Then
dateListNotMinggu.RemoveAt(j)
Exit For
End If
Next
Next
Note that it is convention to use i as a first option for a loop counter, then j for the first nested loop, then k for the second nested loop. You should only use something else if you have good reason to do so. Remember that the loop counter doesn't represent the value in the list but rather its index. That's why you use i for index and not d for date or the like.
EDIT:
As per Jimi's comment below, the way this would usually be tackled is with a simple LINQ query. If you were using LINQ then you definitely wouldn't be using an ArrayList but rather a List(Of Date). In that case, the code would look like this:
dateListNotMinggu = dateListNotMinggu.Except(dateListDead).ToList()
If you were completely insane and wanted to use LINQ and ArrayLists then this would work:
dateListNotMinggu = New ArrayList(dateListNotMinggu.Cast(Of Date)().
Except(dateListDead.Cast(Of Date)()).
ToArray())
Take note that, as I replied in the comments, using LINQ will generate a new list, rather than changing the existing one.

Visual basic list box

I am trying to get each item in a list box into a string array. However, I keep getting an index error and I am not sure why. I am doing this so i can perform a LINQ on the array. Here is the error and the code in question. Thank you for any help in advance.
Error:
InvalidArgument=Value of '16' is not valid for 'index'.
Parameter name: index
Code:
Dim size As Integer = lstBoxSeats.Items.Count()
Dim seats(size) As String
For i = 0 To size
seats(i) = lstBoxSeats.Items(i).ToString()
Next
Your array is zero based, the count is actual number of items. You need to subtract 1 from the count for your index.
i.e.
Correction: just realized that you were using count to dimension your seats array which is leaving a empty position in your seats array
Dim size As Integer = lstBoxSeats.Items.Count()-1 'Subtract 1 here instead of in the For statement
Dim seats(size) As String
For i = 0 To size
seats(i) = lstBoxSeats.Items(i).ToString()
Next
This is because index is zero based i.e starts from 0 while Count is the amount of items which starts from 1, so if there are 16 items it means that maximum index is 15 (0-15) and count is 16(1-16)