3.5 以上代码使用了 LocationCollection 集合类,使用泛型集合创建该类(同样位于 APP_Code 目录下):
using System.Collections.Generic;
public class LocationCollection:List<Location>
{
}
3.6 在 APP_Code 目录下创建 DAO 类用于访问数据库,添加必要的命名空间引用:
using System;
using System.Data;
using System.Data.SqlClient;
public class DAO
{
}
3.7 编写 GetLocations 方法,返回所在地集合对象(请根据实际情况修改数据库连接字符串):
public LocationCollection GetLocations()
{
LocationCollection locs = new LocationCollection();
using (SqlConnection conn = new
SqlConnection("server=.;uid=sa;pwd=00000000;database=temp;"))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "pr_GetLocations";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
SqlDataReader reader = cmd.ExecuteReader();
int level = 0;
int oldlevel = 1;
LocationCollection container=new LocationCollection();
LocationCollection current = new LocationCollection();
while (reader.Read())
{
Location loc = GetLocationFromReader(reader, out level);
if (level == 0)
{
locs.Add(loc);
container.Add(loc);
}
else
{
if (oldlevel != level)
{
container.Clear();
foreach (Location l in current)
container.Add(l);
current.Clear();
oldlevel = level;
}
current.Add(loc);
CreateLocation(container, loc);
}
}
}
return locs;
}
本文来源:不详 作者:佚名