0

I'm not really good at programming and I don't know what's happening in my codes, it works well before but now I get this error:

NullReferenceException was unhadled by user code.

Object Reference not set to an instance of an object.

Here's my code:

 void GetProfileInfo()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "SELECT FirstName, LastName, Address, ContactNo, EmailAddress FROM Users " +
            "WHERE UserID=@UserID";
        cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = Session["userid"].ToString();
        SqlDataReader data = cmd.ExecuteReader();
        while (data.Read())
        {
            txtFN.Text = data["FirstName"].ToString();
            txtLN.Text = data["LastName"].ToString();
            txtAddress.Text = data["Address"].ToString();
            txtContact.Text = data["ContactNo"].ToString();
            txtEmail.Text = data["EmailAddress"].ToString();
        }
        con.Close();
    }
6
  • 2
    What line throws the error? Commented Jun 23, 2013 at 20:03
  • this line: cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = Session["userid"].ToString(); Commented Jun 23, 2013 at 20:09
  • 2
    Then Session["userid"] return null and you try to convert to a string. Commented Jun 23, 2013 at 20:10
  • 1
    It's time to learn some basic debugging skills. Commented Jun 23, 2013 at 20:11
  • I'm sorry guys, i'm not really good at this. I want to learn though, what should I do :) Commented Jun 23, 2013 at 20:13

1 Answer 1

1

First you have to check all occurrences where Session["userid"] is initialized, then in order to avoid exception error you have to check this variable value whether is null or wrap the code with try catch finally blocks

Ex:

try
{
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "SELECT FirstName, LastName, Address, ContactNo, EmailAddress FROM Users " +
            "WHERE UserID=@UserID";
        cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = Session["userid"].ToString();
        SqlDataReader data = cmd.ExecuteReader();
        while (data.Read())
        {
            txtFN.Text = data["FirstName"].ToString();
            txtLN.Text = data["LastName"].ToString();
            txtAddress.Text = data["Address"].ToString();
            txtContact.Text = data["ContactNo"].ToString();
            txtEmail.Text = data["EmailAddress"].ToString();
        }
}
catch(Exception e)
{
    string message = e.Message;
    MessageBox.Show(message);
}
finally
{
        con.Close();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.