C# NullReferenceException was unhandled by user code

Ozzy490 picture Ozzy490 · Mar 28, 2013 · Viewed 30.8k times · Source

Any help on this will be greatly appreciated. Whenever I run my program, I get a NullReferenceException was unhandled by user code.

So when I start the program I have a form appear where I am supposed to choose from a list of names and be able to update the details or delete them, but nothing appears in the drop down list.

I get the null reference at:

comm.Parameters["@EmployeeID"].Value =
employeesList.SelectedItem.Value;

This is the select button in the CS file:

protected void selectButton_Click(object sender, EventArgs e)
{
    // Declare objects
    SqlConnection conn;
    SqlCommand comm;
    SqlDataReader reader;
    // Read the connection string from Web.config
    string connectionString =
        ConfigurationManager.ConnectionStrings[
        "HelpDesk"].ConnectionString;
    // Initialize connection
    conn = new SqlConnection(connectionString);
    // Create command
    comm = new SqlCommand(
        "SELECT FirstName, LastName, Username, Address, City, County, Post Code, " +
        "HomePhone, Extension, MobilePhone FROM Employees " +
        "WHERE EmployeeID = @EmployeeID", conn);
    // Add command parameters
    comm.Parameters.Add("@EmployeeID", System.Data.SqlDbType.Int);
    comm.Parameters["@EmployeeID"].Value =
        employeesList.SelectedItem.Value;
    // Enclose database code in Try-Catch-Finally
    try
    {
        // Open the connection
        conn.Open();
        // Execute the command
        reader = comm.ExecuteReader();
        // Display the data on the form
        if (reader.Read())
        {
            firstnameTextBox.Text = reader["FirstName"].ToString();
            lastnameTextBox.Text = reader["lastName"].ToString();
            userNameTextBox.Text = reader["Username"].ToString();
            addressTextBox.Text = reader["Address"].ToString();
            cityTextBox.Text = reader["City"].ToString();
            countyTextBox.Text = reader["county"].ToString();
            postcodeTextBox.Text = reader["Post Code"].ToString();
            homePhoneTextBox.Text = reader["HomePhone"].ToString();
            extensionTextBox.Text = reader["Extension"].ToString();
            mobilePhoneTextBox.Text = reader["MobilePhone"].ToString();
        }
        // Close the reader 
        reader.Close();
        // Enable the Update button
        updateButton.Enabled = true;
        // Enable the Delete button
        deleteButton.Enabled = true;
    }
    catch
    {
        // Display error message
        dbErrorLabel.Text =
            "Error loading the employee details!<br />";
    }
    finally
    {
        // Close the connection
        conn.Close();
    }
}

And this the code in the aspx file:

<p>
<asp:Label ID="dbErrorLabel" ForeColor="Red" runat="server" />
Select an employee to update:<br />
<asp:DropDownList ID="employeesList" runat="server" />
<asp:Button ID="selectButton" Text="Select" runat="server"
    onclick="selectButton_Click" />

Answer

MisterXero picture MisterXero · Mar 28, 2013

Put a breakpoint at:

comm.Parameters["@EmployeeID"].Value =
        employeesList.SelectedItem.Value;

When you run you program check the value of:

employeesList.SelectedItem

Most likely this will be null if no item has been selected. Try checking for a null value before using:

 if (employeesList.SelectedItem != null)
 {
comm.Parameters["@EmployeeID"].Value =
    employeesList.SelectedItem.Value;
 }
 else
 {
// Handle this case
 }

Hope this helps!