Question

There is already an open DataReader associated with this Command which must be closed first

Asked by: megnin

I'm trying to set the text of a lable to the count returned from a stored procedure but I get this error:
"There is already an open DataReader associated with this Command which must be closed first."

Visual Studio sort of "highlights" in gray a few lines that I assume are causing the problem, but I don't know how to close the offending open DataReader.  

In the Form_Load, this line is highlighted:
"cbCaseManagers.DataSource = CaseManagersTableAdapter.GetDataByCaseManagerName(cbOneStop.SelectedValue.ToString)"

This whole sub for a ComboBox is highlighted:
    Private Sub cbCaseManagers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbCaseManagers.SelectedIndexChanged
        Try
            Me.WTPTableAdapter.FilterByCombination(Me.SigmaToolsDataSet.WTP, CStr(cbOneStop.SelectedValue), CStr(cbCaseManagers.SelectedValue), FromDate.Value, ToDate.Value, CStr(cbReviewer.SelectedValue), cbReviewType.Text)
        Catch ex As System.Exception
            System.Windows.Forms.MessageBox.Show(ex.Message)
        End Try
    End Sub

This is the line throwing the error:

Private Sub WTPDataGridView_RowStateChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowStateChangedEventArgs) Handles WTPDataGridView.RowStateChanged
        If Not IsNothing(cbCaseManagers.SelectedValue) Then
            If TypeOf (cbCaseManagers.SelectedValue) Is String Then
                lblMandatory.Text = CStr(WTPTableAdapter.sp_ScalarQuery_CountMandatory(cbOneStop.SelectedValue.ToString, CStr(cbCaseManagers.SelectedValue), FromDate.Value, ToDate.Value, CStr(cbReviewer.SelectedValue), CStr(cbReviewer.SelectedValue)))
            End If
        End If
    End Sub

                                  
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-13 at 14:19:41ID24809352
Tags

Visual Basic 2008

,

DataGridView

,

TableAdapter

Topics

Microsoft Visual Basic.Net

,

.NET

,

.NET Framework 3.x versions

Participating Experts
2
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Datareader and combo
    VB.Net Windows form How do you use a datareader as a datasource for a combobox and if you do can you set the combos Value and Display members? Wing
  2. Search a value in a datareader
    What is the best way to search a value (string type) in a datareader (all columns) ?
  3. Using a DataReader to fill in a ComboBox
    Hi, I'd like to know how to fill a ComboBox using a DataReader and insert an empty line in tha ComboBox. Usually I do this using a DataSet/DataView but I know that can be done with a DataReader but how? I fill the DataReader as follows: Connection.Open() Di...
  4. DataReader Count
    Hey Guys: I'm trying to figure out how i can retrive how many recorsds the reader read, thi is what i got: Sub SelectTop(ByVal SiteID As Integer, ByVal TableName As String) Dim strSQL2 As String = "SELECT TOP 1 PERCENT * FROM " & TableName & "...
  5. DataGridView Stored Proc DataReader
    I want to create a DataGridView with a Stored Proc with parameters and the data Source. When I set the data source of the DataGridView the view returns no rows (or columns) because the parameter is not provided and the DataGridView does not display columns when there are no ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: emoreauPosted on 2009-10-13 at 18:00:18ID: 25566295

 

by: HainKurtPosted on 2009-10-13 at 18:55:07ID: 25566617

can you please show code for this

WTPTableAdapter.sp_ScalarQuery_CountMandatory

or put a breakpoint here and "step into" here when prg hits this to find where the exact problem is...

 

by: megninPosted on 2009-10-14 at 05:47:06ID: 25569820

I put a breakpoint there and the program loops through it a couple of times then stops with the open DataReader exception right there on the lblMandatory.Text = "Count..." line in the WTPDataGridView_RowStateChanged event handler.  The whole .vb file is <150 lines.  I can post it if you want but here is the stored procedure for setting the label to the count of "Y"s in the GridView with the filters set.

WTPTableAdapter.sp_ScalarQuery_CountMandatory :

ALTER PROCEDURE dbo.sp_ScalarQuery_CountMandatory
(
	@OneStop varchar(50),
	@CaseManagerLName varchar(50),
	@FromDate smalldatetime,
	@ToDate smalldatetime,
	@ReviewerName varchar(50),
	@ReviewType varchar(50)
)
AS
	SET NOCOUNT ON;
SELECT        COUNT(1) 
FROM            WTP
WHERE        (OneStop LIKE @OneStop) AND (CaseManagerLName LIKE @CaseManagerLName) AND (ReviewDate BETWEEN @FromDate AND @ToDate) AND 
                         (ReviewerName LIKE @ReviewerName) AND (ReviewType LIKE @ReviewType) AND (Mandatory LIKE 'Y')

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: emoreauPosted on 2009-10-14 at 05:53:39ID: 25569875

have you read my short article? by default you can only have a single DataReader opened at a single time. my article shows you how to modify your connection string to be able to open more then one.

 

by: megninPosted on 2009-10-14 at 06:11:27ID: 25570014

I'm reading through it now.  If I *only* modify the connection string will it allow that line to work or do I have to throw in the BeginExecuteXXX and EndExecuteXXX somewhere?  (I'm not quite finished reading the article)

 

by: emoreauPosted on 2009-10-14 at 07:40:50ID: 25571021

The BeginExecuteXXX is for asynchronous read which is not what you are trying to do. Are you using SQL 2005? Can you show your new connection string?

 

by: megninPosted on 2009-10-14 at 07:54:28ID: 25571201

I'm not sure how to tell the procedure to use the connection string from the app.config so I put it in the code.

I haven't modified my connection string yet to try your method because I wasn't sure how much I would have to change my code to implement it.  I'm just learning, so the more changes I have to make to something the more likely I'll either break it or get to a point that I don't understand what it's doing and can't maintain it.

So, for now I tried doing it like this.  It seems to work but this is all to count the results of only one question.  I have 43 questions to report the counts of so this doesn't look like the best solution:

    Private Sub WTPDataGridView_RowStateChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowStateChangedEventArgs) Handles WTPDataGridView.RowStateChanged
        lblCount.Text = "Count: " & CStr(WTPDataGridView.RowCount - 1)
        If (Not IsNothing(cbCaseManagers.SelectedValue)) And (Not IsNothing(cbOneStop.SelectedValue)) Then
            If TypeOf (cbCaseManagers.SelectedValue) Is String Then
                'Dim sConnStr As String = ConfigurationManager.ConnectionStrings("CSPConnectionString1").ConnectionString
                Dim DBConn As New SqlClient.SqlConnection("Data Source=BETASERVE;Initial Catalog=SigmaTools;Integrated Security=True;")
                Dim SQLCmd As New SqlClient.SqlCommand("sp_ScalarQuery_CountMandatory", DBConn)
                SQLCmd.CommandType = Data.CommandType.StoredProcedure
                DBConn.Open()
                Try
                    SQLCmd.Parameters.Add("@OneStop", SqlDbType.VarChar).Value = CStr(cbOneStop.SelectedValue)
                    SQLCmd.Parameters.Add("@CaseManagerLName", SqlDbType.VarChar).Value = CStr(cbCaseManagers.SelectedValue)
                    SQLCmd.Parameters.Add("@FromDate", SqlDbType.SmallDateTime).Value = CStr(FromDate.Value)
                    SQLCmd.Parameters.Add("@ToDate", SqlDbType.SmallDateTime).Value = CStr(ToDate.Value)
                    SQLCmd.Parameters.Add("@ReviewerName", SqlDbType.VarChar).Value = CStr(cbReviewer.SelectedValue)
                    SQLCmd.Parameters.Add("@ReviewType", SqlDbType.VarChar).Value = CStr(cbReviewType.Text)
                    Dim varCount As Integer = CInt(SQLCmd.ExecuteScalar())
                    lblMandatory.Text = "Count of Mandatory: " & CStr(varCount)
                Catch ex As Exception
                    System.Windows.Forms.MessageBox.Show(ex.Message)
                End Try
 
                DBConn.Close()
 
            End If
        End If
    End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

Select allOpen in new window

 

by: emoreauPosted on 2009-10-14 at 08:01:42ID: 25571310

try (you need to do it on every connection strings you have):

Dim DBConn As New SqlClient.SqlConnection("Data Source=BETASERVE;Initial Catalog=SigmaTools;Integrated Security=True;MultipleActiveResultSets=True;")



 

by: megninPosted on 2009-10-14 at 08:09:47ID: 25571414

Well, using the method in the code box just above, I don't have the exception problem because I'm opening a new connection anyway.

If I just add "MultipleActiveResultSets=True" to the connection string in my app.config file can I then go back to the method where I only have the line:


lblMandatory.Text = "Count of Mandatory: " & CStr(WTPTableAdapter.sp_ScalarQuery_CountMandatory(CStr(cbOneStop.SelectedValue), CStr(cbCaseManagers.SelectedValue), FromDate.Value, ToDate.Value, CStr(cbReviewer.SelectedValue), cbReviewType.Text))

...instead of that whole block of code in the two nested If/Then blocks?

 

by: emoreauPosted on 2009-10-14 at 08:17:09ID: 25571526

I have no idea! It is really hard for me to follow you when I don't have the complete picture.

­­>>I don't have the exception problem because I'm opening a new connection anyway.

Don't forget that ADO.net is pooling the connections. Just add the additional parameter to all your connection strings and your problem will be solved.

 

by: megninPosted on 2009-10-14 at 08:34:11ID: 25571749

I added "MultipleActiveResultSets=True" to the connection string in the app.config, removed that whole block of code (all the DBConn, SQLCmd stuff) and put the on line back in:

"lblMandatory.Text = "Count of Mandatory: " & CStr(WTPTableAdapter.sp_ScalarQuery_CountMandatory..."

and it works.

Now I think I can add a stored procedure for each of the 43 questions (ugh!) and a similar line to run each of them unless there is a better way.

 

by: emoreauPosted on 2009-10-14 at 08:35:58ID: 25571776

you can surely do a query (or a stored proc) that will return all the data you need in a single request to the server.

 

by: megninPosted on 2009-10-14 at 10:05:38ID: 25572654

Could you elaborate on that a little?  Like I said, I'm just learning this stuff.  If there's a simple solution I'd like to learn how to do it.

Are you saying that it's possible to return the counts of all the questions in a single query?

Right now the stored procedure (in comment ID:25569820) is just returning the count of "Y" values in the "Mandatory" column.  There are 42 additional columns I need to do the same with. (count "Y"s currently displaying in the GridView as a result of the filters selected by the combo boxes)

 

by: emoreauPosted on 2009-10-14 at 10:13:54ID: 25572723

it is not really clear to me what you are trying to do! Remember that we don't have access to your stuff.

do you mean that Mandatory have 42 different values? that would give you this:

SELECT      Mandatory ,  COUNT(1)
FROM            WTP
WHERE        (OneStop LIKE @OneStop) AND (CaseManagerLName LIKE @CaseManagerLName) AND (ReviewDate BETWEEN @FromDate AND @ToDate) AND
                         (ReviewerName LIKE @ReviewerName) AND (ReviewType LIKE @ReviewType)
group by Mandatory

or if you have 42 fields like mandatory, you could union them:

SELECT     'Mandatory',   COUNT(1)
FROM            WTP
WHERE        (OneStop LIKE @OneStop) AND (CaseManagerLName LIKE @CaseManagerLName) AND (ReviewDate BETWEEN @FromDate AND @ToDate) AND
                         (ReviewerName LIKE @ReviewerName) AND (ReviewType LIKE @ReviewType) AND (Mandatory LIKE 'Y')

UNION

SELECT     'YourSecondField',   COUNT(1)
FROM            WTP
WHERE        (OneStop LIKE @OneStop) AND (CaseManagerLName LIKE @CaseManagerLName) AND (ReviewDate BETWEEN @FromDate AND @ToDate) AND
                         (ReviewerName LIKE @ReviewerName) AND (ReviewType LIKE @ReviewType) AND (YourSecondField LIKE 'Y')

UNION

SELECT     'YourThirdField',   COUNT(1)
FROM            WTP
WHERE        (OneStop LIKE @OneStop) AND (CaseManagerLName LIKE @CaseManagerLName) AND (ReviewDate BETWEEN @FromDate AND @ToDate) AND
                         (ReviewerName LIKE @ReviewerName) AND (ReviewType LIKE @ReviewType) AND (YourThirdField LIKE 'Y')

UNION

....

 

by: megninPosted on 2009-10-14 at 10:36:03ID: 25572970

The database contains records created by the submission of a questionaire like form that asks for FirstName, LastName (unimportant), CaseManager, Reviewer, OneStop, FromDate, ToDate, ReviewType.  Those six fields are used as parameters in the stored procedure to filter the data displayed in the GridView.  In addition to those fields are 43 questions.  Each question is a field or column in the record.  "Mandatory" is one of the 43 question columns.  The question can be answered either "Y" or "N" so when the GridView is filtered using the combo boxes the  stored procedure counts the displayed "Y" answers in that one column (of 43), currently only "Mandatory".

Yes, I think the UNION query is exactly what I would need.  Possibly two of them because I may also need to count the "N" responses to each question.

Yes, each part of the UNION query would be identical except for the 'YourSecondField', 'YourThirdField' would be different for each, just like you've shown.

 

by: megninPosted on 2009-10-19 at 13:58:09ID: 31640785

That UNION query works like a charm.  I've also created a stored procedure from it.  Awesome.  Thank you again, very much!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...