質問

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(); 
            }
        }
    }
}
役に立ちましたか?

解決

try this

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

                    }
                    else
                    {
                        Console.WriteLine("No rows found.");
                    }

他のヒント

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())
{ ...}

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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top