locked
Invalid attempt to call HasRows when reader is closed RRS feed

  • Question

  • User426012303 posted

    Hi, I encounter this error when I run the program.

    protected void btnSubmit_Click(object sender, EventArgs e)
            {
               vrm_database vd = new vrm_database();
                // create the data adapter
                int countRows = gvCC.Rows.Count;
    
                string  strSQL = "";
                
                int[] arr = new int[countRows];
    
                for (int i = 0; i < arr.Length; i++)
                {
                    strSQL = "SELECT targetedamt FROM [VRM].[Contract] WHERE vendorbrn = '" + gvCC.Rows[i].Cells[2].ToString() + "'";
    
                    SqlDataReader dr = vd.Get_TargetAmt(strSQL);
                    
                    int amt = 0;
    
                    if (dr.HasRows)
                    {
                       while (dr.Read())
                        {
                            amt += Convert.ToInt32(dr[0].ToString());
                        }
                    
                    }
    
                    dr.Close();
                    Label1.Text = "$" + amt;
                }
    
            }
    Tuesday, August 23, 2011 2:46 AM

All replies

  • User-68639941 posted

    you sholud not close connection in getReader method bcose sqldatareadre works on active sql connection

    hi,

    your connection object should be in opened mode, unitl you have completed the reading i.e till the  while (dr.Read()) completed

     i hope the connection object is closed within the function Get_TargetAmt. so dont do that after reading the value close the connection object

    Refer : http://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.80).aspx

    Tuesday, August 23, 2011 2:52 AM
  • User426012303 posted

    So for the Get_TargetAmt i have to close the connection?

    public SqlDataReader Get_TargetAmt(string sqlStr)
            {
                SqlCommand cmd = new SqlCommand(sqlStr);
    
                return getReader(cmd);
            }
    Tuesday, August 23, 2011 4:53 AM