错误.未设置为对象实例的对象引用

本文关键字:实例 对象引用 对象 设置 错误 | 更新日期: 2023-09-27 17:51:14

之前一切正常。我所做的唯一的事情是添加了一个编辑按钮,然后这个错误发生了。即使我撤消编辑按钮,错误仍然存在。谁能告诉我第26行有什么问题吗?

SqlCommand cmdDoctorInfo = new SqlCommand("SELECT d.* FROM Doctorinfo p, Department d WHERE d.DepartmentID = p.DepartmentID AND p.userId = @UserID", conDoctorInfo);
Line 26:   cmdDoctorInfo.Parameters.AddWithValue("@UserID", Session["UserId"].ToString()); 
SqlDataReader dtrPatient = cmdDoctorInfo.ExecuteReader();

编辑:由于一些未知的原因,它突然工作后,我关闭和打开应用程序一遍又一遍。当我添加回Edit Button时,错误又回来了。这是编辑按钮代码(第二行)

<td align="center">
                    <asp:Button ID="editButton" runat="server" OnClick="editButton_Click" Text="Edit" />
                    <asp:FileUpload ID="picFileUpload" runat="server"/>
                    <asp:Button ID="uploadButton" runat="server" OnClick="uploadButton_Click" Text="Upload"/>
                    <br />
                    <asp:Label ID="messageLabel" runat="server" ForeColor="Red"></asp:Label>
                </td>

我不明白为什么添加编辑按钮会导致错误。

错误.未设置为对象实例的对象引用

可能是您的Session["UserId"]为空。试试这个:

cmdDoctorInfo.Parameters.AddWithValue("@UserID",Convert.ToString(Session["UserId"]));

转换。即使Session["UserId"]为空,ToString也不会破坏你的代码。因为Convert.ToString()处理null,而ToString()不处理。

在您显示的代码中唯一可以是null的对象是Session对象。如果ToString为null,则会导致此错误。

你可以检查:

object userIdObj = Session["UserId"];
if(userIdObj != null)
{
    // use the correct type, i presume int
    int userID = int.Parse(userIdObj.ToString());
    cmdDoctorInfo.Parameters.AddWithValue("@UserID", userID);
}