I'm currently trying to create a method that allows me to run any query on a connectionstring, and get the results returned in a readable way for my ASP.Net website. Because I need access to all rows and columns a query might need, I cannot simply return a string or an array of strings. If I return a SqlDataReader, I'm not able to read the data outside of the method, because the connection is closed.
This is what my method currently looks like.
private SqlDataReader QueryConnectionString (string query)
{
// New SQL Connection
SqlConnection cnn;
// New Connection String
string connetionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
// Instantiate the SQL Connection with Connection String
cnn = new SqlConnection(connetionString);
// Create a SqlCommand with the input Query
SqlCommand command = new SqlCommand(query, cnn);
cnn.Open();
// Create a SqlDataReader and tie it to the query
SqlDataReader reader = command.ExecuteReader();
cnn.Close();
return reader;
}
In my other methods I would have something like this
SqlDataReader reader = QueryConnectionString("SELECT * FROM tTable");
lblOutput.Text = reader.GetString(0);
But doing so gives me the error
System.InvalidOperationException: 'Invalid attempt to call CheckDataIsReady when reader is closed.'
I realize that returning a SqlDataReader is not an option. What can I return the data as so that other methods can read the data?