-1

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 .......

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
No One
  • 42
  • 1
  • 1
  • 6

2 Answers2

2

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.

  • Thanks Bro. Yup Exactly, That is the Question Arised in My Mind About string to int ........... !! – No One Jun 28 '16 at 11:27
1

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

You are actually trying to access element from array by index which is expected to be int and you are accessing it by name which throws error.

HttpCookie httpCookie = new HttpCookie("UserInfo");
httpCookie.Values.Add("Name", NameTextBox.Text);
httpCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(httpCookie);
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40