简体   繁体   中英

C# stop on null reference

during the login sequence of my program, I check for the existance of the user in the admin table

If they don't exist in the admin table, I want the program to then stop executing the rest of the login sequence and update a label text on the login screen to show why they cannot login etc...

At the moment the label doesn't update with the text and this would be down to refreshing the page before changing the text.

I also have other checks that occur during login that could stop them from logging in.

What would be the best approach in the case to ensure based on certain checks, a different label text can be displayed each time?

Thanks for your help

try
{
    conn.Open();
    string checkAdmin = "Select Username from Admins where Username= '" + Session["Username"] + "'";

    SqlCommand adminCheck = new SqlCommand(checkAdmin, conn);
    string admin = adminCheck.ExecuteScalar().ToString();
    conn.Close();
    Session["Admin"] = admin;
}
catch (NullReferenceException)
{

    Session.Abandon();
    Response.Redirect(Request.RawUrl);
    Label3.Text = "blablabla"
}

EDIT

OK I have updated it now based on your comments to....

                try
            {

                string checkAdmin = "Select Username from Admins where Username= @User";
                conn.Open();
                SqlCommand adminCheck = new SqlCommand(checkAdmin, conn);
                adminCheck.Parameters.AddWithValue("@User", Session["Username"]);
                var admin = adminCheck.ExecuteScalar();
                conn.Close();
                if (admin != null)
                {
                    Session["Admin"] = admin;


                }

                else 
                {
                    Session["Admin"] = null;
                }

            }
            catch (Exception)
            {

            }
 Response.Redirect(Request.RawUrl); 

This will immediately cancel the execution of the current code, and transfer to the that URL (presumably some other code). Therefore the following statement, to change the label, will not be executed.

From the documentation (remarks section):

Redirect calls End which throws a ThreadAbortException exception upon completion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM