0

Everything was working fine before. The only thing I did was added an Edit Button, then this error occurred. Even though I undo the Edit Button, the error still persist. Can anyone tell me what is wrong with line 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: For some unknown reason, it suddenly works fine after I closed and opened the app over and over again. Now when I add back the Edit Button, the error comes back. Here is the Edit Button code (2nd line)

<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>

I don't understand how does adding an Edit button cause the error. Please enlighten me.

user2741620
  • 305
  • 2
  • 7
  • 21

2 Answers2

6

May be your Session["UserId"] is null. try this:

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

Convert.ToString will not break your code even Session["UserId"] is null. Because Convert.ToString() handles null, while ToString() doesn't.

Muhammad Omair
  • 797
  • 4
  • 14
  • If it solved your issue please mark my answer as up.:) – Muhammad Omair Mar 21 '14 at 07:56
  • `Convert.ToString` can break your code even more since it could silently swallow an exceptional `UserID` (`null`). I guess that he gets a database error now. But even if not it's better to handle the case that it's `null` more explicitly. – Tim Schmelter Mar 21 '14 at 07:59
  • Yeah logically Convert.ToString affect your system if it will not break your code but is another approach to handle exception for String. – Muhammad Omair Mar 21 '14 at 08:03
  • 1
    @MuhammadOmair: exceptions are a good thing if they prevent you from incorrect data in your database. So not the exception is the bug which has to be fixed. – Tim Schmelter Mar 21 '14 at 08:29
2

The only object which can be null in the code you are showing is the Session object. You are using ToString which results in this error if it's null.

You could check that:

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);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939