我一直在尝试添加到列表列表中,添加来自 sql 数据库的信息。将新信息添加到列表时出现的错误是:
“在 StatusScope.dll 中发生类型为‘System.NullReferenceException’的异常,但未在用户代码中处理
附加信息:未将对象引用设置到对象的实例。"
我该如何解决这个错误?
map 逻辑.cs
public static List<MapModel.ClientInfo> GetClientsData()
{
SqlConnection Connection = site.Models.Shared.DBConnection.GetConnection();
SqlDataReader Reader = null;
SqlCommand Command = new SqlCommand("SELECT DocInfo.DocID, DocInfo.DocName, DocInfo.DocPic, DocInfo.PatientAcceptance, ClientInfo.ClientName, ClientInfo.AddressLocal, ClientInfo.AddressBroad, ClientInfo.Phone, ClientInfo.Lat, ClientInfo.Long, ClientInfo.ClientID FROM DocInfo INNER JOIN ClientInfo ON DocInfo.ClientID = ClientInfo.ClientID;", Connection);
Reader = Command.ExecuteReader();
var ClientsData = new List<MapModel.ClientInfo> { };
int IDCounter = 0;
bool FirstRun = false;
while (Reader.Read())
{
if (!FirstRun)
{
ClientsData.Add(new MapModel.ClientInfo { Id = IDCounter, ClientID = Reader["ClientID"].ToString(), ClientName = Reader["ClientName"].ToString(), DocPic = Reader["DocPic"].ToString(), PatientAcceptance = Reader["PatientAcceptance"].ToString(), AddressLocal = Reader["AddressLocal"].ToString(), AddressBroad = Reader["AddressLocal"].ToString(), Phone = Reader["Phone"].ToString(), latitude = Reader["Lat"].ToString(), longitude = Reader["Long"].ToString(), DocNames = { } });
FirstRun = true;
}
else
{
for (var x = 0; x < ClientsData.Count; x++)
{
if (ClientsData[x].ClientID == Reader["ClientID"].ToString())
{
ClientsData[x].DocNames.Add("123"); //error occurs here
}
else
{
ClientsData.Add(new MapModel.ClientInfo { Id = IDCounter, ClientID = Reader["ClientID"].ToString(), ClientName = Reader["ClientName"].ToString(), DocPic = Reader["DocPic"].ToString(), PatientAcceptance = Reader["PatientAcceptance"].ToString(), AddressLocal = Reader["AddressLocal"].ToString(), AddressBroad = Reader["AddressLocal"].ToString(), Phone = Reader["Phone"].ToString(), latitude = Reader["Lat"].ToString(), longitude = Reader["Long"].ToString() });
}
}
}
IDCounter++;
}
Connection.Close();
return ClientsData;
}
map 模型.cs
public class ClientInfo
{
public int Id { get; set; }
public string ClientID { get; set; }
public string ClientName { get; set; }
public List<string> DocNames { get; set; }
public string DocPic { get; set; }
public string PatientAcceptance { get; set; }
public string AddressLocal { get; set; }
public string AddressBroad { get; set; }
public string Phone { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
}
您是否曾经将 DocNames
设置为任何内容?如果不是,它将为空。
在 ClientInfo
的构造函数中你应该有
DocNames = new List<string>();
初始化一个空列表。
我是一名优秀的程序员,十分优秀!