Search code examples
c#asp.nethttpcookie

Error message "Cannot implicitly convert type 'String' to 'Int'"


I keep getting the debug error "cannot implicitly convert type 'string' to 'int'".

I bold the Text where I got that error.

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie httpCookie = Request.Cookies["UserInfo"];

        if (httpCookie == null)
        {
            txtDiv.Visible = true;
        }
        else
        {
            msgDiv.Visible = true;
            string userName = httpCookie.Values["Name"].ToString();
            WelcomeLabel.Text = "Welcome Back Mr. "+userName;
        }
    }

    protected void SignupButton_Click(object sender, EventArgs e)
    {
        // Error in Below Line.
        HttpCookie httpCookie = new HttpCookie["UserInfo"];
        httpCookie.Values.Add("Name", NameTextBox.Text);
        httpCookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(httpCookie);

        Response.Redirect("Thanks.aspx?name="+NameTextBox.Text);
        // Server.Transfer("Thanks.aspx");
    }

I also Change it to new HttpCookie["UserInfo"].ToString(); but error .......


Solution

  • Change HttpCookie httpCookie = new HttpCookie["UserInfo"]; to HttpCookie httpCookie = new HttpCookie("UserInfo");

    But the reason why the 'string' to 'int' error is coming up is because [] is used for an index of an array, [int]. So it is trying to covert a string into an int.