A Question of Dorknozzle | Retrieve value from QueryString

Hi,

I bought ‘Build your own ASP.NET 2.0’ a couple of years back and have finally summonned up the confidence to start learning :smiley:

I’m on Chapter 9 discussing ADO.NET and have a query about reading a unique data value from a table.


<%@ Page Title="" Language="C#" MasterPageFile="~/Dorknozzle.master" AutoEventWireup="true" CodeFile="BlogEntry.aspx.cs" Inherits="BlogEntry" %>
<%@ Import Namespace = "System.Data.SqlClient" %>

<script runat="server">

  protected void Page_Load(object sender, EventArgs e)
  {
    // Define database connection
    SqlConnection conn = new SqlConnection(
        "Server=localhost\\\\SqlExpress;Database=Dorknozzle;" +
        "Integrated Security=True");
    // Create command
    SqlCommand comm = new SqlCommand(
        "SELECT ID, Title, Body, DatePosted FROM Entries WHERE ID = 1", conn);
    // Open connection
    conn.Open();
    // Execute the command
    SqlDataReader reader = comm.ExecuteReader();
    // Read and display the data
      while(reader.Read())
      {
          employeesLabel.Text += reader["Title"] + "<br />";
          employeesLabel.Text += reader["Body"] + "<br />";
          employeesLabel.Text += reader["DatePosted"] + "<br />";
      }
    // TODO: Do something with the data
    // Close the reader and the connection
    reader.Close();
    conn.Close();
  }
</script>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
  <asp:Label ID="employeesLabel" runat="server" />
</asp:Content>

My Question is how do I retrieve the value from the Query String to use in my SELECT query?
So BlogEntry.aspx?ID=1 would retrieve the entry where ID = 1.

And is the above the best way to do this, or should I try move things to my CodeBehind file?

Many thanks for any input you have.

you can retrieve the value like this

string ID = Request[“ID”];

then you can use ID in your query

Yes, as stated on above. Just on a side note. It is better to keep your code on the code behind page. It is just better for abstraction

Great stuff! Many thanks for the speedy reply.

I quite agree NightStalker. I’m very new to .NET so right now it’s a horrible mess, but ultimately I will move it to CodeBehind :slight_smile:

Thanks again