Reputation: 59
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();
}
Upvotes: 0
Views: 228
Reputation: 4212
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();
}
Upvotes: 1