-2

I am trying to bind data to a label when it is the same as the query string that I have. I keep getting a error saying.

Must declare the scalar variable "@YouthClubID".

Here is my code.

      using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;


namespace WebApplication1
{
    public partial class youthclubpage : System.Web.UI.Page
    {
        int YouthClubID;

       protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlConnection sqlConnection = new SqlConnection("server = sql7.hostinguk.net; uid = joanton7865org7272_phelim; pwd = Armo32nk; database = joanton7865org7272_youthpodcast;"))
            {
                sqlConnection.Open();
                string strSQL = "Select youthclubname from youthclublist WHERE ([YouthClubID] = @YouthClubID)";
                using (SqlCommand sqlCommand = new SqlCommand(strSQL, sqlConnection))
                {
                    sqlCommand.Parameters.AddWithValue("@YouthClubID", Request.QueryString["club"]);
                    txtClubName.Text = sqlCommand.ExecuteScalar() + "";
                }
            }
        }
        }


    }
Inkey
  • 2,189
  • 9
  • 39
  • 64

4 Answers4

3

The error happens, as others said already, because you're not populating the Parameter defined in the SQL statement.

Anyway, you don't need Adapter at all, in your case ExecuteScalar method is enough:

using (SqlConnection sqlConnection = new SqlConnection("..."))
{
    sqlConnection.Open();
    string strSQL = "Select youthclubname from youthclublist WHERE ([YouthClubID] = @YouthClubID)";
    using (SqlCommand sqlCommand = new SqlCommand(strSQL, sqlConnection))
    {
        sqlCommand.Parameters.AddWithValue("@YouthClubID", Request.QueryString["club"]);
        txtClubName.Text = sqlCommand.ExecuteScalar() + "";
    }
}

In the above I assumed the club ID is passed as page.aspx?club=[id here] meaning the query string variable name is "club", change to the real name of course.

The + "" part is meant to put empty text in case there is no matching value in database.
When there is no such value, sqlCommand.ExecuteScalar() will return null - having the plain way of:

txtClubName.Text = sqlCommand.ExecuteScalar().ToString();

Will generate error in such case - by adding empty string the conversion to string occurs automatically and it looks more pretty. See this question as well. Needless to say, if the value is not null, it won't be changed.

Community
  • 1
  • 1
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • @Inkey So change `Request.QueryString["club"]` to `Request.QueryString["CategoryID"]`. That's what I meant in *meaning the query string variable name is "club", change to the real name of course.* – Shadow The GPT Wizard Feb 01 '12 at 11:52