我正在尝试从 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/