Afternoon All,

I have ran into a problem that i cant get my head around,
I have the following code(see below) this all works fine if there is a imgID ='5'
but if there isn't a record in the sql table with the imgID 5 then i get the following error

Indexoutofrangeexception was unhandeled, there is no row at position 0
which just tells me that no record exists.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Using conn As New System.Data.SqlClient.SqlConnection("Data Source=localhost;Initial Catalog=ImageGallery;Persist Security Info=True;User ID=mbish;Password=mbish") 'insert your connection string
            conn.Open()
            Using cmd As New SqlClient.SqlCommand("Select Imagecontent From ImageCollection where imgID ='5'", conn)
                Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader()
                    Using dt As New DataTable
                        dt.Load(dr)
                        Dim row As DataRow = dt.Rows(0)
                        Using ms As New IO.MemoryStream(CType(row("ImageContent"), Byte()))

                            Dim img As Image = Image.FromStream(ms)
                            image1.Image = img
                        End Using

                    End Using
                End Using
            End Using
        End Using
        Me.image1.SizeMode = PictureBoxSizeMode.StretchImage
    End Sub

I have tried

if dt.rows(0) = 0 then end sub

in vb6 i would put if EOF then End sub

would this work?

If dt.Rows.Count = 0 Then Exit Sub
                        Dim row As DataRow = dt.Rows(0)

like mike said,

i dont use sqlclient, but i use adodb.

whenever I run a query, i test that it is not the end of file (recordset.eof = false) before I do anything with the data. This way if it is end of file, it moves on to the next.


be careful with sqlclient as it might be like the mysqlclient and move to the second row once you perform the .read test

this worked fine for me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.