I am using C#
I am trying to check whether my login attempt is not more than 3, I mean with the below condition:
if (((int)Session["LoginAttempt"]) != 3)
{
}
In Login failed condition I am doing increment like below:
Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;
But it is giving me this error: "Object reference not set to an instance of an object."
Suggestions please!
Sorry Guys,
I just changed the integer converting code from
((int) Session["LoginAttempt"])
to
Convert.ToInt32(Session["LoginAttempt"]) + 1;
and now it is working fine for me, please suggest incase of any issues in it.
Thanks!
Why not encapsulate the LoginAttempt value as a property and auto-assign a value:
protected int LoginAttempt
{
get
{
if (Session["LoginAttempt"] == null)
{
Session["LoginAttempt"] = 1;
}
return Convert.ToInt32(Session["LoginAttempt"].ToString());
}
set
{
Session["LoginAttempt"] = value;
}
}
so that the main body of the function is more readable:
if (LoginAttempt < 3)
{
}
Try the magic code:
Session["LoginAttempt"] = ((int?)Session["LoginAttempt"] ?? 0) + 1;
This will convert the session variable Session["LoginAttempt"]
to a nullable int
(an int
that can be null
) the ?? 0
provides a value 0 if it is null, so the calculation succeeds.
The Session["LoginAttempt"]
can be null if it is not initialized before.
You need to test to see if the Session
variable exists before you can use it and assign to it.
Here you are doing an increment:
Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;
But, if the Session["LoginAttempt"]
does not exist, this will explain your error. A quick null
test before the increment should sort it out.
if (Session["LoginAttempt"] != null)
Session["LoginAttempt"] = ((int)Session["LoginAttempt"]) + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With