0

我不太擅长编程,我不知道我的代码中发生了什么,它以前运行良好,但现在我收到此错误:

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();
    }
4

1 回答 1

1

首先,您必须检查Session["userid"]初始化的所有事件,然后为了避免异常错误,您必须检查此变量值是否为空或用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();
}
于 2013-06-23T20:17:51.907 回答