?
Solved

ExecuteReader requires an open and available Connection. The connection's current state is closed

Posted on 2009-07-13
2
Medium Priority
?
1,329 Views
Last Modified: 2013-11-07
My datagrid has a large number of dropdown lists that are displayed when the user chooses to edit a row.  Something about the procedure I've tried to add to generically populate each list is conflicting with the connection state.   I can't see what so would appreciate help.  Exceptoin thrown is below, as is the code of the procedure run on databind and the procedure that one calls for populating the dropdown lists.

Error occurs after the call loadDropDown(e, "pet_type", colPetType2, "ddPetType");
on the line:  SqlDataReader reader = cmd.ExecuteReader();

Just as a note, at one point I tried passing the open conn in to the loadDropDown call rather than opening and closing a connection in the sub-proc but that had the same problem.

System.InvalidOperationException was unhandled by user code
  Message="ExecuteReader requires an open and available Connection. The connection's current state is closed."
  Source="System.Data"
  StackTrace:
       at System.Data.SqlClient.SqlConnection.GetOpenConnection(String method)
       at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
       at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader()
       at Webkinz.MasterItems.loadDropDown(DataGridItemEventArgs e, String queryfield, Int32 col_index, String ddl_name) in C:\All\Visual Studio 2008\Projects\Webkinz\Webkinz\MasterItems.aspx.cs:line 240
       at Webkinz.MasterItems.gridItems_ItemDataBound(Object sender, DataGridItemEventArgs e) in C:\All\Visual Studio 2008\Projects\Webkinz\Webkinz\MasterItems.aspx.cs:line 212
       at System.Web.UI.WebControls.DataGrid.OnItemDataBound(DataGridItemEventArgs e)
       at System.Web.UI.WebControls.DataGrid.CreateItem(Int32 itemIndex, Int32 dataSourceIndex, ListItemType itemType, Boolean dataBind, Object dataItem, DataGridColumn[] columns, TableRowCollection rows, PagedDataSource pagedDataSource)
       at System.Web.UI.WebControls.DataGrid.CreateControlHierarchy(Boolean useDataSource)
       at System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e)
       at System.Web.UI.WebControls.BaseDataList.DataBind()
       at Webkinz.MasterItems.loadGrid() in C:\All\Visual Studio 2008\Projects\Webkinz\Webkinz\MasterItems.aspx.cs:line 166
       at Webkinz.MasterItems.gridItems_Edit(Object source, DataGridCommandEventArgs e) in C:\All\Visual Studio 2008\Projects\Webkinz\Webkinz\MasterItems.aspx.cs:line 264
       at System.Web.UI.WebControls.DataGrid.OnEditCommand(DataGridCommandEventArgs e)
       at System.Web.UI.WebControls.DataGrid.OnBubbleEvent(Object source, EventArgs e)
       at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
       at System.Web.UI.WebControls.DataGridItem.OnBubbleEvent(Object source, EventArgs e)
       at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
       at System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:

protected void gridItems_ItemDataBound(object sender, DataGridItemEventArgs e)
        {          
            if (e.Item.ItemType == ListItemType.EditItem)
            {
                string curr_val = e.Item.Cells[colItemType2].Text;
                DropDownList ddl = null;
                ddl = (DropDownList)e.Item.FindControl("ddItemType");
 
                SqlConnection conn = new SqlConnection(c.getConnectionString());
                using (conn)
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand("webkinzGetCategories", conn);
                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Clear();
                    SqlDataReader reader = cmd.ExecuteReader();
                    try
                    {
                        ddl.Items.Clear();
                        while (reader.Read())
                        {
                            ListItem li = new ListItem(reader["category"].ToString(),reader["category"].ToString());
                            if (curr_val == reader["category"].ToString())
                                li.Selected = true;
                            ddl.Items.Add(li);
                        }
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
                conn.Close();
 
                loadDropDown(e, "pet_type", colPetType2, "ddPetType");
                loadDropDown(e,  "theme", colTheme2, "ddTheme");
                loadDropDown(e,  "item type", colItemClass2, "ddClassification");
                loadDropDown(e,  "Source", colSource2, "ddlSource");
                loadDropDown(e,  "Gift Occasion", colGift2, "ddGift");
                loadDropDown(e,  "GEV Category", colGEVCategory2, "ddGEVCategory");
                loadDropDown(e,  "GEV Rule", colGEVRule2, "ddGEVRule");                                
 
                TextBox txt = (TextBox)e.Item.FindControl("txtFileName");
                curr_val = e.Item.Cells[colImage2].Text;
                if (curr_val.Length < 5 || curr_val == "&nbsp;") return;
                txt.Text = curr_val;
 
            }
 
        }
        protected void loadDropDown( DataGridItemEventArgs e, string queryfield, int col_index,string ddl_name)
        {
 
            SqlConnection conn = new SqlConnection(c.getConnectionString());
            string curr_val = e.Item.Cells[col_index].Text;
            DropDownList ddl = (DropDownList)e.Item.FindControl(ddl_name);
            using (conn)
            {
                string queryString = "select [" + queryfield + "] from WebKinzMasterItems where [" + queryfield + "] is not null group by [" + queryfield + "] order by [" + queryfield + "]";
                SqlCommand cmd = new SqlCommand(queryString, conn);
                cmd.CommandType = CommandType.Text;            
                cmd.Parameters.Clear();
                SqlDataReader reader = cmd.ExecuteReader();
                try
                {
                    ddl.Items.Clear();
                    while (reader.Read())
                    {
                        ListItem li = new ListItem(reader[queryfield].ToString(), reader[queryfield].ToString());
                        if (curr_val == reader[queryfield].ToString())
                            li.Selected = true;
                        ddl.Items.Add(li);
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
            conn.Close();     
        }

Open in new window

0
Comment
Question by:deb_holmes
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 9

Accepted Solution

by:
Rahul Goel ITIL earned 1500 total points
ID: 24838687
add conn.open() at line number 61
0
 

Author Closing Comment

by:deb_holmes
ID: 31602775
actually needed to be between 55 and 58
0

Featured Post

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

752 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