views:

58

answers:

3

hi, I´m trying to use session to store a value (id). The problem is that I have to store it as a string. When trying to use the instance of the id I get the error:

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:

Line 156:        
Line 157:        Nemanet_Navigation newFile = new Nemanet_Navigation();
Line 158:        newFile.Nav_pID = (Guid)Session["id"];
Line 159:       
Line 160:    

This is where I get the id and that seems to work fine. Session["id"] gets the value.

public void treeview_Navigation_SelectedNodeChanged(object sender, EventArgs e)
    {

        TreeNode node = treeview_Navigation.FindNode(treeview_Navigation.SelectedNode.ValuePath);
        NavTreeNode nNode = node as NavTreeNode;
        Session["id"]=((TreeView)sender).SelectedValue.ToString();
     }

But this code does not seem to work. I get the error mentioned above.

protected void Button1_Click(object sender, EventArgs e)
    {


        Nemanet_Navigation newFile = new Nemanet_Navigation();
        newFile.Nav_pID = (Guid)Session["id"];
       }
+4  A: 

Use Guid.Parse

protected void Button1_Click(object sender, EventArgs e)
{
    Nemanet_Navigation newFile = new Nemanet_Navigation();
    newFile.Nav_pID = Guid.Parse(Session["id"] as string);
}
Randolpho
You'll need to cast `Session["id"]` to a `string` before you can pass it to the `Parse` method.
LukeH
@LukeH: good point. Fixed
Randolpho
+2  A: 

Try using:

newFile.Nav_pID = new Guid(Session["id"].ToString());
Mike
thanks this works:)
A: 

You are converting GUID to string before saving it in session collection. But when you are retrieving it, you are trying to cast it in GUID which is invalid. String and GUID are not compatible types. Either save it as GUID or convert it into string (like you are doing) when saving and use GUID constructor that takes string to reform GUID instance.

You can do it like this:

Session["id"]=((TreeView)sender).SelectedValue.ToString();

and then retrieve it from session like:

newFile.Nav_pID = new Guid((string)Session["id"]);
cornerback84