When to close a datareader and connection?

Posted on 2008-11-14
Last Modified: 2012-05-05
I have the following code below in a shared function within a self-created namespace. My question is; when and where should I close the datareader and connection. I am assuming that in this example if I close the datareader after 'End While' it will be too late as the the function will have already executed its return of X.

I am assuming the same is true if I close the datareader after the 'End If'

Or am I completely wrong? and if so... where do I close the datareader/connection.
If oDR.HasRows = True Then

                    While oDR.Read

                        Return X

                    End While


                    Return 0

                End If

Open in new window

Question by:footballencounters
    LVL 9

    Accepted Solution

    You're correct, it would be too late.  Consider a variable to hold your return value, whether it is X or 0, and return it after the End If after you've closed the DataReader.

    Also, if you're only going to return the one value, you don't need a while look.  If oDR.Read() then would accomplish the same.
    LVL 9

    Expert Comment

    instead of returning x in the loop assign it to a variable.

    the code will then exit out the loop and this is where you close your connection / reader.

    the code will then exit the if statment and its here where you should return the value

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
    In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
    This video discusses moving either the default database or any database to a new volume.
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now