rebma amber rebma amber - 2 months ago 18
ASP.NET (C#) Question

Login error message object reference

I have two pages called

Login.aspx
and
Home.aspx


UPDATED CODE:

protected void Button1_Click(object sender, EventArgs e)
{

if (loginmethod(txt_us.Text, txt_pwd.Text) != "NA")
{
FormsAuthentication.Initialize();
String strRole = Assignroles(txt_us.Text);
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, txt_us.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, strRole, FormsAuthentication.FormsCookiePath);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(fat)));
loginmethod(txt_us.Text, txt_pwd.Text);
Response.Redirect("home.aspx");
}
else if (Session["ID"] != null)
{

u = Session["ID"].ToString();
}

else
{
Label1.Text = ("Incorrect UserName/Password");

Label1.Visible = true;
Response.Redirect("home.aspx");
}
txt_us.Text = "";
txt_pwd.Text = "";
}

private string loginmethod(string UserName, string Password)
{
try
{
login_class lg_class = new login_class();
Entities login = new Entities();
string logn = Convert.ToString(lg_class.loginfunction(UserName, Password).Rows[0]["id"]);
Session["ID"] = logn.ToString();
return (logn);
}
catch (Exception ex)
{
return (ex.Message.ToString());
}
}

private string Assignroles(string username)
{
if ((txt_us.Text != string.Empty) && (txt_pwd.Text != string.Empty))
return "";
else
return string.Empty;
}

public DataTable loginfunction(string username, string password)
{
try
{
Entities lg = new Entities();
List<SP_GetLogin_Result> gr = lg.SP_GetLogin(username, password).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
foreach (var l in gr)
{
dt.Rows.Add(l.id);
}
return dt;
}
catch (Exception)
{
throw new Exception();
}
}


And on
home.aspx
page load:

string id;

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
id = Session["ID"].ToString();
this.FFID = "All";
vehcileinfo(id);
}
}


SP_GetLogin
return ID i.e. when i enter username
abc
and pssword
1224
then this return ID
CU-2343


when i enter with correct username and password then this redirect to
home.aspx


But when i enter wrong username or password then this show an error on this line

u = Session["ID"].ToString();



System.NullReferenceException: Object reference not set to an
instance of an object.


And i want to show error message on
login.aspx

"incorrect username and password"

How i do this?

Div Div
Answer

As per discussion in a comments, get an exception of NullReferenceException

Which means, you are trying to use something that is null. This means you either set it to null, or you never set it to anything at all.

So, just check on Page_Loadof Home.aspx

if(Session["ID"] != null)
{ 
   id = Session["ID"].ToString();
} 

else
{
  // Do logic here
} 
Comments