我不擅长编程,我不知道我的代码中发生了什么,它之前运行良好,但现在我收到了这个错误:
NullReferenceException未被用户代码取消。
对象引用未设置为对象的实例。
这是我的代码:
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();
}
答案 0 :(得分:1)
首先,您必须检查初始化Session["userid"]
的所有事件,
那么为了避免异常错误你必须检查这个变量值是否为null或用try catch finally
块包装代码
前:
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();
}