数据是空的。 在C#.net中连接两个表后,无法在空值上调用此方法或属性

在我的代码中加入表后,出现错误“数据为空。此方法或属性无法在空值上调用”。

请查看我的代码,请帮忙。 我试图在谷歌寻找答案,但仍然没有得到我想做的。

这是导致上述错误的代码:

private static string m_sConnectionString = ConfigurationManager.ConnectionStrings["NomsConnection"].ConnectionString; private static string m_sReport = "SELECT r.[RequestID],r.[RequestDate],r.[PARNumber],r.[StatusID],r.[PurchaseComment]" // 0 - 4 + ",r.[UID],r.[MyUID],r.[FullName],r.[Email]" // 5 - 8 + ",r.[EntityName],r.[DepartmentName],r.[DepartmentID]" // 9 - 11 + ",r.[LastBy]" // 12 + ",r.[ProgramID],r.[ProgramCode],r.[ProgramName],r.[CostCenterCode]" // 13 - 16 + ",p.[PartDesc],p.[SupplierID],p.[AccountType],p.[CurrName],p.[PartQuantity],p.[PiecePrice]" + "FROM [NOP_PR].[dbo].[Requests] r " + "JOIN [NOP_PR].[dbo].[Parts] p on p.[RequestID] = r.[RequestID]" + "WHERE [CountryName] IN ('Philippines')"; public static List LoadPRRequestFromDB(DateTime from, DateTime to) { string sSrcipt = m_sReport + "and [RequestDate] between '" + from.ToString("yyyy-MM-dd HH:mm:ss") + "' and '" + to.ToString("yyyy-MM-dd HH:mm:ss") + "'"; Dictionary data = new Dictionary(); long key; double dAmount; using (SqlConnection con = new SqlConnection(m_sConnectionString)) { con.Open(); using (SqlCommand command = new SqlCommand(sSrcipt, con)) { SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { key = reader.GetInt64(0); if (!data.ContainsKey(key)) { data.Add(key, new NomsPRRequest() { RequestID = key ,RequestDate = reader.GetDateTime(1) ,PARNumber = reader.GetString(2) ,StatusID = reader.GetInt64(3) ,FullName = reader.GetString(7) ,LastBy = reader.GetString(12) ,ProgramName = reader.GetString(14) ,ItemList = new List() ,TotalAmount = 0.0 }); } dAmount = (double)reader.GetDecimal(21) * (double)reader.GetDecimal(22); data[key].TotalAmount += dAmount; data[key].ItemList.Add(new NomsPRItem() { RequestID = key, PartDesc = reader.GetString(17) ,SupplierID = reader.GetString(18) ,AccountType = reader.GetString(19) ,CurrName = reader.GetString(20) ,PartQuantity = (double)reader.GetDecimal(21) ,PiecePrice = (double)reader.GetDecimal(22) ,Amount = dAmount }); } } } return data.Values.ToList(); } } 

由于我的数据库中的[LastBy]列只有空值..我只是添加了Luann所说的:) ..感谢分享Luann!

  data[key].ItemList.Add(new NomsPRItem() { ,RequestDate = reader.GetDateTime(1) ,PARNumber = reader.GetString(2) ,StatusID = reader.GetInt64(3) ,FullName = reader.GetString(7) ,LastBy = reader.IsDBNull(12) ? null : reader.GetString(12) ,ProgramName = reader.GetString(14) ,ItemList = new List() ,TotalAmount = 0.0 }); 

在读取可空列的值之前,需要使用reader.IsDBNull

例如:

 PartDesc = reader.IsDBNull(17) ? null : reader.GetString(17)