c# - C#、SQL 2005、VS 2008 中的 "Object reference not set to an instance of an object."

标签 c# sql

我正在尝试从 SQL Server 2005 的“t_Food”表中选择“food_ItemName”和“food_UnitPrice”。

我有以下代码:

private void GetDatabaseConnection()
{
    string connectionString = @"Server = RZS-F839AD139AA\SQLEXPRESS; Integrated Security = SSPI; Database = HotelCustomerManagementDatabase";
    connection = new SqlConnection(connectionString);
    connection.Open();
}

还有......

public Food PopulateFoodItemListview()
{
    GetDatabaseConnection();
    string selectFoodItemQuery = @"SELECT food_ItemName, food_UnitPrice FROM t_Food";
    SqlCommand command = new SqlCommand(selectFoodItemQuery, connection);
    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        food.ItemName.Add(reader.GetString(0));  // Exception is generated in this line
        food.UnitPrice.Add(reader.GetDouble(1));
    }
    connection.Close();
    return food;
}

在食品类中,我有以下代码:

public class Food
{
    private List<string> itemName;
    private List<double> unitPrice;
    private double itemUnit;
    private Customer foodCustomer = new Customer();

    public Food ()
    {
    }

    public Food(List<string> itemName, List<double> unitPrice) : this()
    {
        this.itemName = itemName;
        this.unitPrice = unitPrice;
    }

    public List<string> ItemName
    {
        get { return itemName; }
        set { itemName = value ; }
    }

    public List<double> UnitPrice
    {
        get { return unitPrice; }
        set { unitPrice = value; }
    }

    public double ItemUnit
    {
        get { return itemUnit; }
        set { itemUnit = value; }
    }
}

但它生成以下异常。为什么?

“未将对象引用设置为对象的实例。”

最佳答案

您需要先创建“itemName”和“unitPrice”变量的实例,然后才能添加到它们中的任何一个。您可以在声明它们时继续执行此操作。

private List<string> itemName = new List<string>();
private List<double> unitPrice = new List<string>();

关于c# - C#、SQL 2005、VS 2008 中的 "Object reference not set to an instance of an object.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3521296/

相关文章:

c# - 从 xml 文件生成 xmldocument 对象的最快方法

c# - 您可以从 C# 控制台应用程序写入 CRM 365 跟踪日志吗?

c# - 获取解决方案中的所有启动项目

c# - 改变数组中的元素

c# - 将方法移到另一个类时无法产生声音

sql - 这是创建SQL断言的正确方法吗?

java - 在 SQL 或 CODE 中更好地对聚合数据进行分组(就性能而言)

sql - 在具有许多关系的表中删除 100 万行的最佳方法

sql - AST 与后缀算法

sql - 从字符串中删除所有元音 - PL/SQL