1

I have a WebMethod which is called to retrieve a varchar(max) column from SQL Server. I create my neccessary stored procedure, which works fine in Management Studio, but when I run the below code I get an error:

Invalid attempt to read when no data is present

Code:

[WebMethod]
public static void PopulatePopUp(string arg)
{
    var str = GlobalStatic.ExceptBlanks(arg);

    SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);

    SqlDataReader rdr = null;

    using (conn)
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            conn.Open();

            cmd.CommandText = "GetMessage_Sel";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@messageId", SqlDbType.VarChar, -1).Value = str;
            cmd.Parameters.Add("@RowCount", SqlDbType.Int).Direction = ParameterDirection.Output;

            cmd.Connection = conn;

            try
            {
                rdr = cmd.ExecuteReader();

                if (rdr.HasRows)
                {
                    string fieldValue = rdr.GetString(0);
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }

                rdr.Close();
            }
            catch (Exception err)
            {
                // handle the error
                //messageInsert = false;
            }
            finally
            { 
                conn.Close(); 
            }
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
CSharpNewBee
  • 1,951
  • 6
  • 28
  • 64

3 Answers3

2

Depending on the rows you expect you would need the Read method called which will actually fetch you the results, so this condition should be good as it would only move in if there is a row to read out

while(rdr.Read())
{...}

OR

if(rdr.Read())
{ ...}
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
2

try this

                    if (rdr.HasRows)
                    {
                        while(rdr.Read())
                        {
                            string fieldValue = rdr[0].ToString();
                        }

                    }
                    else
                    {
                        Console.WriteLine("No rows found.");
                    }
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
  • School boy error. thanks guys. Changing my code to accept a read (idiot i am) i now get a cast issue. Int32 to a string. I was under the impression that -1 in the declaration is for a Varchar(max) – CSharpNewBee Jul 10 '13 at 09:11
1

That happened because you have not read next record.

Change

if (rdr.HasRows)
{
    string fieldValue = rdr.GetString(0);
}

to

if (rdr.Read())
{
    string fieldValue = rdr.GetString(0);
}
gzaxx
  • 17,312
  • 2
  • 36
  • 54