Dave Goosem
Dave Goosem

Reputation: 568

Query String Value always 0

This is likely an easy one, but I cannot see what is wrong..

I have this string being added to my url: /projects.aspx?pid=3

and in my code behind I am trying to grab this value like so:

public partial class Projects : System.Web.UI.Page
{
    public int pid { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            pid = Convert.ToInt32(Request.QueryString["pid"]); //this is returning 0 when it should have a value.
            DataBind(true);

            PopulateTestSuiteList();
        }

        TestSuitesDataList.ItemCommand += new RepeaterCommandEventHandler(this.Item_Command);
    }

When I try look at the value of pid in my other functions, it always gives me '0'. I don't see why won't it give me 3 like it should?

Here are example functions:

private void ExecuteInsert(string TestSuiteName, string TestSuiteDescription, int ProjectID)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        string sql = "INSERT INTO TestSuites (ProjectID, TestSuiteName, TestSuiteDescription) VALUES " + " (@ProjectID,@TestSuiteName,@TestSuiteDescription)";
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);

            SqlParameter[] param = new SqlParameter[3];

            param[0] = new SqlParameter("@TestSuiteName", SqlDbType.NVarChar, 50);
            param[1] = new SqlParameter("@TestSuiteDescription", SqlDbType.NVarChar, 200);
            param[2] = new SqlParameter("@ProjectID", SqlDbType.Int);

            param[0].Value = TestSuiteName;
            param[1].Value = TestSuiteDescription;
            param[2].Value = pid;

            for (int i = 0; i < param.Length; i++)
            {
                cmd.Parameters.Add(param[i]);
            }

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }

    protected void AddTestSuiteButton_Click(object sender, EventArgs e)
    {
        //checks whether the test suite name already exists in the database and stops duplicates from being added for the same project
        string checkExistsQuery = "SELECT TestSuiteName FROM TestSuites WHERE TestSuiteName = @TestSuiteName and @ProjectID = " + pid;

        SqlConnection conn = new SqlConnection(GetConnectionString());
        SqlCommand checkExistsCmd = new SqlCommand(checkExistsQuery, conn);

        SqlParameter c1 = new SqlParameter("TestSuiteName", TxtTestSuiteName.Text);
        SqlParameter c2 = new SqlParameter("ProjectID", pid);

        checkExistsCmd.Parameters.Add(c1);
        checkExistsCmd.Parameters.Add(c2);

        conn.Open();

        SqlDataReader rd = checkExistsCmd.ExecuteReader();

        if (rd.HasRows)
        {
            lblAddTestSuiteMessage.Text = "Oops, a Project with that name already exists.";
            rd.Close();
            conn.Close();
        }
        else
        {
            string FormattedTestSuiteDescription = TxtTestSuiteDescription.Text.Replace("\r\n", "<br />");
            //call the method to execute insert to the database
            ExecuteInsert(TxtTestSuiteName.Text, FormattedTestSuiteDescription, pid);

            lblAddTestSuiteMessage.Text = "Project has been added successfully";
            ClearControls(Page);
        }

        rd.Close();
        conn.Close();
        Response.Redirect(Request.RawUrl);
    }

In the same code behind, this function seems to be happily pulling the correct data and displaying it on my page - it is using the PID as well??

        private void PopulateTestSuiteList()
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        conn.Open();
        string sql = "SELECT TestSuiteID, ProjectID, TestSuiteName, TestSuiteDescription FROM TestSuites WHERE ProjectID = " + pid + "ORDER BY TestSuiteName ASC";
        SqlCommand cmd = new SqlCommand(sql, conn);

        SqlDataReader rd = cmd.ExecuteReader();
        while (rd.Read())
        {
            TestSuitesDataList.DataSource = rd;
            TestSuitesDataList.DataBind();
        }
        conn.Close();
    }

Upvotes: 1

Views: 2812

Answers (3)

शेखर
शेखर

Reputation: 17614

Since your are using Convert.ToInt32 as

 Convert.ToInt32(Request.QueryString["pid"]);

And if it is null Convert.ToInt32 function will return 0.

Try using Int32.Parse(Request.QueryString["pid"]) and see weather you get the null value exception or not.

If yes there is no value for pid in your Query string. Check from where you are sending pid in query string.

More over

You can also use Session as value might be lost on edit or update event. So you can do it as follows

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       if(Request.QueryString["pid"]!=null && Session["pid"]!=null)
        pid = Convert.ToInt32(Request.QueryString["pid"]); 
        DataBind(true);
        PopulateTestSuiteList();
    }
    TestSuitesDataList.ItemCommand += new RepeaterCommandEventHandler(this.Item_Command);
}

and inside your function ExecuteInsert function

private void ExecuteInsert(string TestSuiteName, string TestSuiteDescription)
{
     SqlParameter c2 = new SqlParameter("ProjectID", Int32.Parse(Session["pid"].ToString()));

Upvotes: 1

muratgu
muratgu

Reputation: 7311

This is probably caused by not fully understanding the page life cycle. You are setting the pid on Page_Load, but probably using it somewhere when page is not yet loaded or re-loaded (e.g. after a postback).

If you get the pid value from query string and need to use it on postback, you need to store it in a session variable or a hidden field on the page. Assigning it to a page class variable will not persist it like you are doing here.

Upvotes: 2

Mahdi Tahsildari
Mahdi Tahsildari

Reputation: 13582

I would check for every inconvenient value such as null or invalid strings, my code would be:

if (Request.QueryString["pid"] != null)
{
    int pid;
    if (int.TryParse(Request.QueryString["pid"].ToString(), out pid))
    {
        //Then its OK and you have an 
        //integer, put the codes here
    }
    else
    { 
        //The query string has value
        //but the value is not valid
        //(not an integer value)
    }
}

Upvotes: 1

Related Questions