SellaKumar
SellaKumar

Reputation: 27

Index was outside the bounds of the array in VB.net

im getting this error printing out the if statement

Index was outside the bounds of the array

Codes:

Private Sub radsingle_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radsingle.CheckedChanged

        With comDB
            .CommandText = SQL
            rdDB = .ExecuteReader
        End With
        While rdDB.Read

            If rdDB(1).ToString = txtptp.SelectedItem.ToString Then
                txtcdays.Text = rdDB(2).ToString.Trim

                'Radmulti.Checked = False
            End If
        End While

        rdDB.Close()

    End Sub

is there anything i've to change in this code..?

Upvotes: 1

Views: 2715

Answers (2)

Abhitalks
Abhitalks

Reputation: 28387

The right way to use DataReader would be something on these lines:

If DataReader.HasRows Then
    While DataReader.Read()
    If rdDB.Item("ColumnName1").ToString = txtptp.SelectedItem.ToString Then
        ...
    End If
    End While
End If

This way you can check if DataReader contains rows or not, and also avoid confusions on index.

Of course, from your posted code it is unclear what the SQL variable holds. Possibly, your query is not returning any rows.

Upvotes: 1

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Try to use Column Name instead of Column Index

Upvotes: 0

Related Questions