1

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

Brian
  • 5,064
  • 7
  • 33
  • 44
Ozzy490
  • 39
  • 1
  • 1
  • 4
  • 1
    NullReference are easiest to fix. Enable break when any exception is thrown from VS. Go to Debug-->Exception. check the Thrown for CLR Exception – Dhawalk Mar 28 '13 at 21:22
  • 1
    Has an item from `employeesList` been selected? – keyboardP Mar 28 '13 at 21:22
  • Why aren't you wrapping your code in a try/catch block? Also, why are you adding the parameter before setting its value? – Brian Mar 28 '13 at 21:29
  • @keyboardP. When I run the program there is noting to select. it's blank. – Ozzy490 Mar 28 '13 at 21:40
  • @user331742 - In that case it would be null which is why you're getting that error. Check MisterXero's answer to see how to check if something is null. – keyboardP Mar 28 '13 at 21:42
  • @user331742 - "What do you mean by try/catch block? " - It's an exception handler. http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.110%29.aspx – PM_ME_YOUR_CODE Mar 28 '13 at 21:43
  • @Brian. I'm new to this. I thought I had done this??? – Ozzy490 Mar 28 '13 at 21:50
  • Debugger is your friend. I ALWAYS wonder on these types of questions when debugger can tell you what's wrong immediately. Please learn how to use it. You will save you some time. – Tomas Voracek Mar 28 '13 at 21:51
  • @TomasVoracek - Debugger isn't telling me anything, it's appearing blank – Ozzy490 Mar 28 '13 at 22:13

3 Answers3

6

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!

MisterXero
  • 1,048
  • 2
  • 8
  • 16
  • It may very well be that `employeesList` is the objec that is null. Attempting to access a property of a null object will throw this error. So your check `employeesList.SelectedItem` may also cause a Null Reference Exception – EtherDragon Mar 28 '13 at 21:37
  • @EtherDragon `employeesList` is a control, so it won't be null. – MikeSmithDev Mar 28 '13 at 21:49
  • @MikeSmithDev But SelectedItem IS null obviously... – Tomas Voracek Mar 28 '13 at 22:25
  • @TomasVoracek I wasn't talking about SelectedItem. I was referring to "It may very well be that `employeesList` is the objec that is null". The control itself will not be null. – MikeSmithDev Mar 28 '13 at 23:15
0

It doesn't look like you added any items to your dropdown list.

You have:

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

But a dropdown list should have items like:

<asp:DropDownList ID="employeesList" runat="server">
    <asp:ListItem Text="Item 1" Value="1" Selected="true" />
    <asp:ListItem Text="Item 2" Value="2"/>
</asp:DropDownList>
Robert Aguilar
  • 106
  • 1
  • 5
  • You may want to add that if the user does not select any items then the SelectedItem may still be null so he should check for null before using it. – MisterXero Mar 28 '13 at 21:53
  • Ideally, the first item should be something like "Select one" or another default value, and then have that with Selected="true". Then check for that value before proceeding. – Robert Aguilar Mar 28 '13 at 21:58
  • I have a table in my database that it is supposed to get the data from and display it in the drop down list – Ozzy490 Mar 28 '13 at 22:02
0

First you have to fill your data in the drop down list from the table available in the database.

Sample Code: In Page_Load,

if (!IsPostBack)
{
   ddlName.DataSource=ds;
   ddlName.DataValueField="ID";
   ddlName.DataTextField="NAME";
   ddlName.DataBind();
}
Afzaal Ahmad Zeeshan
  • 14,868
  • 10
  • 50
  • 94
RGS
  • 4,825
  • 4
  • 29
  • 52