none
How to create a 'blank' or 'empty' SqlDataReader RRS feed

  • Question

  •  

    This is probably simple. I have a function in which I pass in a string and return an SqlDataReader. I assign the Reader inside a try. I am getting an error, because the SqlDataReader may not always have a value.

     

    How can I assign an empty Reader???

     

    ConnectionString is a global variable

     

    private SqlDataReader ExecuteQueryGetReader( string Query )

    {

    SqlDataReader Reader;

    using (SqlConnection Conn = new SqlConnection(ConnectionString))

    {

    SqlCommand Comm = new SqlCommand(Query, Conn);

    try

    {

    Conn.Open();

    Reader = Comm.ExecuteReader();

    }

    catch (Exception exp)

    {

    Log("Error: " + exp.ToString());

    }

    finally

    {

    Conn.Close();

    }

    }

    return Reader;

    Wednesday, March 19, 2008 6:34 PM

Answers

All replies

  • what error are you getting?

     

    if the DataReader is empty you will get an error if you try to get values form it (e.g. dr.GetString(0)) but there is no reason while this code would fail unless there is a problem with your SQL Statement.

     

    Wednesday, March 19, 2008 6:41 PM
  • It won't compile.

     

    It gives: Use of unassigned local variable 'Reader'

    Wednesday, March 19, 2008 6:48 PM
  • try this:

     

    SqlDataReader reader = null;

    Wednesday, March 19, 2008 9:25 PM