I am trying to have the contents of a datatable be displayed in a listbox. I cannot, however, figure out what is wrong with my code; I am pretty sure I have tried every way but the right way. I have search through StackOverflow, and the internet in general for an answer, but I cannot find any relevent information. The error I keep getting is:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: There is no row at position 1.
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count()
lstBoxSaved.Items.Add((dt.Rows(i).Item(0).ToString) & " " &
MessageBox.Show("Please clear table", "error: too many entries")
You're problem is that the way your loop is written it goes past the last element, which is where the exception is thrown. For example, if you have 1 row in the table the index of that row in the collection of rows is 0. The first time the loop happens,
dt.Rows(i) will get the first row in the table (index 0). The next time the loop happens,
i will be 1. So when
dt.Rows(i) happens again, it's trying to grab the second row in the table, which does not exist. So, because the rows are indexed starting at 0, you want to loop to the number of rows minus 1.
For i As Integer = 0 To dt.Rows.Count() should be
For i As Integer = 0 To dt.Rows.Count() - 1