reading a cookie to show a panel
I am trying to read a cookie from the user computer, if this cookie existing , then i will show him a pa开发者_C百科nel1 , if not , panel2 will be visible.
i guess this work will be done in the page_load code block , so here is my code
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["test"].Value)
{
Panel1.Visible = false;
Panel2.Visible = true;
}
}
the problem is it highlighted Request.Cookies["test"].Value
as an erorr , saying
"Error> Cannot implicitly convert type 'string' to 'bool'"
Any suggestions ?
using c# , visiual studio 2010 express, web forms.
First of all Request.Cookies["test"]
may be null (if there is no cookie), so you need to test for that.
Request.Cookies["test"].Value
returns a string, not a boolean. The if
statement can only operate on boolean expressions.
You can use string.IsNullOrWhiteSpace
to check the value of the cookies - it will return true if there is no value or if it only contains whitespace and false otherwise:
if (Request.Cookies["test"] != null && !string.IsNullOrWhiteSpace(Request.Cookies["test"].Value))
{
Panel1.Visible = false;
Panel2.Visible = true;
}
精彩评论