<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
protected void Page_Load(object sender, EventArgs e)
{
//调用增加TreeView根节点的方法
AddRootNodes();
}
///
/// 增加根节点
///
private void AddRootNodes()
{
//配置Sql查询语句和参数(行政区划级别=1/省级)
string strSQL = "SELECT * FROM [District] WHERE [DistrictLevel]=@DistrictLevel";
SqlParameter[] paras = new SqlParameter[]
{
new SqlParameter("@DistrictLevel",1)
};
//调用GetDataSet()方法得到数据集
DataSet ds = GetDataSet(strSQL, paras);
//遍历得到的所有节点
foreach (DataRow row in ds.Tables[0].Rows)
{
//实例化根节点,并赋值
TreeNode rootNode = new TreeNode();
rootNode.Text = row["DistrictName"].ToString();
rootNode.NavigateUrl = string.Format("~/ShowDistrict.aspx?DistrictId={0}", row["DistrictId"].ToString());
rootNode.Value = row["DistrictId"].ToString();
//调用添加该节点的子节点的方法
AddChildNodes(rootNode);
//添加TreeView的根节点
TreeView1_District.Nodes.Add(rootNode);
}
}
///
/// 添加子节点的方法
///
///
private void AddChildNodes(TreeNode rootNode)
{
//配置Sql查询语句和参数
string strSQL = "SELECT * FROM [District] WHERE [ParentDistrictId]=@ParentDistrictId";
SqlParameter[] paras = new SqlParameter[]
{
new SqlParameter("@ParentDistrictId",rootNode.Value)
};
//得到数据集DataSet
DataSet ds = GetDataSet(strSQL, paras);
//遍历数据集中所有的子节点
foreach (DataRow row in ds.Tables[0].Rows)
{
//实例化子节点并赋值
TreeNode childNode = new TreeNode();
childNode.Text = row["DistrictName"].ToString();
childNode.NavigateUrl = string.Format("~/ShowDistrict.aspx?DistrictId={0}", row["DistrictId"].ToString());
childNode.Value = row["DistrictId"].ToString();
//迭代,添加该子节点的所有子节点
AddChildNodes(childNode);
//将该字节点添加到根节点中
rootNode.ChildNodes.Add(childNode);
}
}
///
/// 方法返回数据集
///
///
///
///
private static DataSet GetDataSet(string strSQL, SqlParameter[] values)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["DistrictDBConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = strSQL;
cmd.Parameters.AddRange(values);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}