user175084
user175084

Reputation: 4640

Checkbox: Display depending on value of session?

I have a two checkboxes on different pages. I am sending the value from the first checkbox using session like this:

protected void Button4_Click(object sender, EventArgs e)
        {
            Session["VSSsnap"] = CheckBox1.Checked;
            Response.Redirect("~/Addnewpolicy4.aspx");
        }

I receive this session like this on the next page:

string vss = Session["VSSsnap"].ToString();

However, I want to put this value in a checkbox on the second page.

I tried this, but I get an error:

CheckBox1.Checked = Session["VSSsnap"].ToString();

I also tried this; when I debug, the values are also present (but not displayed by checkbox):

CheckBox1.Checked.Equals(Session["VSSsnap"]);

Any help would be greatly appreciated.

Upvotes: 0

Views: 1952

Answers (3)

Michael Edwards
Michael Edwards

Reputation: 6528

You are not casting the value from the Session. Try:

CheckBox1.Checked =  (bool) (Session["VSSsnap"] ?? false);

The ?? check to ensure that if VSSsnap is null for any reason false will be returned.

Upvotes: 2

LukeH
LukeH

Reputation: 269608

The Checked property of the checkbox is a bool, not a string.

You're trying to assign a string to the Checked property which is why you're getting an error.

Try this instead:

CheckBox1.Checked = (bool)(Session["VSSsnap"] ?? false);

Upvotes: 1

MRG
MRG

Reputation: 3219

Use below code :

if( Session["VSSsnap"] != null )
{
 CheckBox1.Checked = Convert.ToBoolean(Session["VSSsnap"]);
}

Upvotes: 1

Related Questions