简体   繁体   中英

VB.NET - There is no row at position 1 - datatable

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) & " " &
                       (dt.Rows(i).Item(1).ToString))
        Next i
    Else
        MessageBox.Show("Please clear table", "error: too many entries")
    End If

Some while ago I was able to get some variant of this to work for one item, but I need to display all items in the datatable. If there is a more efficient way to display an entire row that would also work.

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

I add a checkbox to grid and check if the checkbox is checked. After that I add select rows to list box.

Dim I As Integer
For I = 0 To DataG1.Rows.Count - 2
    Dim row As DataGridViewRow = DataG1.Rows(I)

    Dim Check As DataGridViewCheckBoxCell = row.Cells(0)

    Dim ID As DataGridViewTextBoxCell = row.Cells(1)
    Dim Name As DataGridViewTextBoxCell = row.Cells(2)
    If Check.Value = True Then
        lstBoxSaved.Items.Add(ID ,Name )
    End If
Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM