0

I would like to set the value "id" to the Session["p_id"] and then use to store it elsewhere in another page. It appears an error "Cannot insert the value NULL into column 'P_Id', table " Here is my code:

//Sample of code from an .aspx page codebehind. Here the value id is retrieved and saved in a Session state.   
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();

string pat_id = "SELECT P_id FROM P_identity WHERE Amka = @amka ";
SqlCommand com2 = new SqlCommand(pat_id, conn);
com2.Parameters.AddWithValue("@amka",TextBoxAmka.Text);

int id = Convert.ToInt32(com2.ExecuteScalar());
 Session["pa_id"] = id;//here i think the problem is

[...]



[...] //another .aspx page codebehind that i want to pass the Session state from the other page, and insert it to the database


protected void btndias_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
        conn.Open();
int id = Convert.ToInt32(Session["pa_id"]);
        string insert_dim1 = "insert into P_dimensions (P_Id,Height,Weight) values (@pa_id, @height, @weight) ";
        SqlCommand com = new SqlCommand(insert_dim1, conn);
        com.Parameters.AddWithValue("@pa_id", id);
        com.Parameters.AddWithValue("@height", txbdi2.Text);
        com.Parameters.AddWithValue("@weight", txbdi1.Text);

        com.ExecuteNonQuery();

        if (note_di.Text.Length != 0)
        {
            string insert_dim2 = "insert into P_dimensions (Note_dim) values (@note_dim) ";
            SqlCommand com2 = new SqlCommand(insert_dim2, conn);
            com2.Parameters.AddWithValue("@note_dim", note_di.Text);
            com2.ExecuteNonQuery();
        }

        Response.Write("<script>alert('Τα στοιχεία αποθηκεύτηκαν επιτυχώς!')</script>");

        conn.Close();
    }
    catch (Exception ex)
    {
        Response.Write("Error :" + ex.ToString());
    }
natso
  • 97
  • 1
  • 12
  • what do you have your session state set to in the web.config? What is the sessionState tag mode set to? – TheTerribleProgrammer Nov 23 '15 at 12:48
  • Where does the error appear exactly? At `Session["p_id"] = pat_id;`? – C4d Nov 23 '15 at 12:49
  • As simple as it is: Your session will probably be `null`. So before setting your session variable, check out if its set or not. Hard to say from this point of view. – C4d Nov 23 '15 at 12:53
  • 3
    Plus your code is saving the query to the session and not the returned id. – TheTerribleProgrammer Nov 23 '15 at 12:54
  • @TheTerribleProgrammer i havent anyhting written in web.config. Do i have to? – natso Nov 23 '15 at 12:54
  • @C4ud3x the error is in: com.Parameters.AddWithValue("@pa_id", Session["p_id"].ToString()); The problem is that i dont know how to set the variable retrieved from the datatable , to a session . (it is an integer) – natso Nov 23 '15 at 12:58
  • Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Rahul Singh Nov 23 '15 at 13:16
  • @RahulSingh i have already read that, but my major problem is how to set a variable retrieved from a table and set it to a session state. I tried my own way (which seems similar to that answer you posted) but unfortunatelly hasnt solved my problem – natso Nov 23 '15 at 13:26
  • FYI `SqlConnection` and `SqlCommand` should always be combined with a [`using` statement](http://www.hanselman.com/blog/WhyTheUsingStatementIsBetterThanASharpStickInTheEyeAndASqlConnectionRefactoringExample.aspx). Also: [don't use `AddWithValue`](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/). – BCdotWEB Nov 23 '15 at 13:41
  • Yes, I already have those usings @BCdotWEB. The code i posted is a sample – natso Nov 23 '15 at 13:43
  • Where/how did you execute that `Session["p_id"] = pat_id` (probably should be `=id`)? Are you sure it's the same session and that it is executed *before* you try to read it? – Hans Kesting Nov 23 '15 at 15:55
  • @HansKesting i tried to change it to Session["p_id"] = id; because it seems more right and the error is persisting. In the first lines, the "id" value is properly inserted in my database... But it doesn't seem to be inserted in the Session state – natso Nov 23 '15 at 16:04
  • 1
    `Session["p_id"]` is **not** getting set **_before_** you click the button. – Rick S Nov 23 '15 at 16:40
  • @RickS the first sample of the code is in another page , into the button click event. My mistake that i didnt mention it.The second sample is in other page and i want to tranfer that value through Session – natso Nov 23 '15 at 16:46
  • @natso - Put a breakpoint after that Session["pat_id"] = id" line. Is the "id" value what you expect? Is the value of Session["pat_id"] the same (should be)? Also check what happens when you use an unknown "amka" value. – Hans Kesting Nov 24 '15 at 09:38
  • @HansKesting I'm sorry, but as a total beginner in asp.net I am not sure how to handle and interpret the breakpoints... Although, I tried another way to solve my problem , but still there is an error. (I will change my code in the main question) – natso Nov 24 '15 at 11:02
  • @natso - using breakpoints ([link](https://msdn.microsoft.com/en-us/library/5557y8b4.aspx)) is a useful skill, especially for a beginner. Now you can *see* what the code does, instead of guessing/hoping. – Hans Kesting Nov 24 '15 at 11:52
  • @HansKesting thanks, i will check it then how to use breakpoints – natso Nov 24 '15 at 12:06
  • Please see ["Should questions include “tags” in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"! –  Nov 24 '15 at 12:57

1 Answers1

0

I finally answered my question. Thank you all for your contribution

  protected void btndias_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();

            int id = Convert.ToInt32(Session["pa_id"]);


            if (note_di.Text.Length != 0)
            {
                string insert_dim2 = "insert into P_dimensions (P_Id,Height,Weight,Note_dim) values (@pa_id, @height, @weight,@note_dim) ";
                SqlCommand com2 = new SqlCommand(insert_dim2, conn);
                com2.Parameters.AddWithValue("@pa_id", id);
                com2.Parameters.AddWithValue("@height", txbdi2.Text);
                com2.Parameters.AddWithValue("@weight", txbdi1.Text);
                com2.Parameters.AddWithValue("@note_dim", note_di.Text);
                com2.ExecuteNonQuery();

            }
            else
            {

                string insert_dim1 = "insert into P_dimensions (P_Id,Height,Weight) values (@pa_id, @height, @weight) ";
                SqlCommand com = new SqlCommand(insert_dim1, conn);
                com.Parameters.AddWithValue("@pa_id", id);
                com.Parameters.AddWithValue("@height", txbdi2.Text);
                com.Parameters.AddWithValue("@weight", txbdi1.Text);
                com.ExecuteNonQuery();
            }


            Response.Write("<script>alert('Τα στοιχεία αποθηκεύτηκαν επιτυχώς!')</script>");

            conn.Close();
        }
        catch (Exception ex)
        {
            Response.Write("Error :" + ex.ToString());
        }
    }
natso
  • 97
  • 1
  • 12