Note that there are some explanatory texts on larger screens.

plurals
  1. POAsp.Net: Returning a Reader from a Class
    text
    copied!<p>I was just wondering about the correct way to return a reader from a class?</p> <p>My code below works, but I'm unsure if this is correct. </p> <p>Also. I can't close the the connection in my class method and still access it from my ascx page, is </p> <p>that OK?</p> <p>// In my class I have the following method to return the record/reader -- it's a single record in this case.</p> <pre><code>public SqlDataReader GetPost() { SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("con_spPost", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@blogid", blogid); try { conn.Open(); return cmd.ExecuteReader(); } finally { // conn.Close(); } } </code></pre> <p>//I then call the GetPost method in my ascx page like so:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { //instantiate our class MyClass DB = new MyClass(); //pass in the id of the post we want to view DB.PostID = Int32.Parse(Request.QueryString["p"]); ///call our GetPost method SqlDataReader reader = DB.GetPost(); //output the result reader.Read(); this.viewpost.InnerHtml = "&lt;span id='post1_CreatedDate'&gt;" + reader["CreatedDate"].ToString() + "&lt;/span&gt;&lt;br&gt;"; this.viewpost.InnerHtml += "&lt;span class='blogheads'&gt;" + reader["BlogTitle"].ToString() + "&lt;/span&gt;&lt;p&gt;&lt;p&gt;"; this.viewpost.InnerHtml += reader["BlogText"].ToString(); reader.Close(); } </code></pre> <p>I'd appreciate any comments on my code or tips, thanks.</p> <p>Melt</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload