C# NullReferenceException was unhandled by user code

This question already has an answer here:

  • What is a NullReferenceException, and how do I fix it? 33 answers

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


    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>
    

    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();
    }
    
    链接地址: http://www.djcxy.com/p/28042.html

    上一篇: “你调用的对象是空的?”

    下一篇: C#NullReferenceException未被用户代码处理