954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

IF sql record doesn't exisit

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

Mike Bishop
Junior Poster
107 posts since Nov 2010
Reputation Points: 7
Solved Threads: 0
 

would this work?

If dt.Rows.Count = 0 Then Exit Sub
                        Dim row As DataRow = dt.Rows(0)
Mike Bishop
Junior Poster
107 posts since Nov 2010
Reputation Points: 7
Solved Threads: 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

jlego
Posting Pro
529 posts since Mar 2009
Reputation Points: 31
Solved Threads: 41
 

this worked fine for me

Mike Bishop
Junior Poster
107 posts since Nov 2010
Reputation Points: 7
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: