用户代码未处理 C# NullReferenceException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15692380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:37:02  来源:igfitidea点击:

C# NullReferenceException was unhandled by user code

c#asp.netsqlnullreferenceexceptionvisual-web-developer-2010

提问by Ozzy490

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

对此的任何帮助将不胜感激。每当我运行我的程序时,我都会收到用户代码未处理的 NullReferenceException。

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:

这是 CS 文件中的选择按钮:

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:

这是aspx文件中的代码:

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

回答by MisterXero

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!

希望这可以帮助!

回答by Robert Aguilar

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>

回答by RGS

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

首先,您必须在数据库中可用表的下拉列表中填写您的数据。

Sample Code: In Page_Load,

示例代码:在 Page_Load 中,

if (!IsPostBack)
{
   ddlName.DataSource=ds;
   ddlName.DataValueField="ID";
   ddlName.DataTextField="NAME";
   ddlName.DataBind();
}