我正在使用链接到SQL服务器的树视图。我有两个桌子区域和街道,区域有很多街道。我填充了我的树视图,在每个区域只有与该区域相关的街道。我的街道到达第一区域,第二个区域节点是街道加上第一个区域节点的街道,依此类推,我需要消除额外的街道。 这是我的代码:
private void PopulateTreeview1()
{
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
SqlCommand cmd1 = cnn.CreateCommand();
cmd1.CommandText = "select areaId,areaName from area";
SqlDataAdapter sdr1 = new SqlDataAdapter(cmd1);
cmd1.CommandType = CommandType.Text;
cmd1.Connection = cnn;
sdr1.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
// Current areaId and areaname is stored
string areaID = dt.Rows[i]["areaId"].ToString();
string areaName = dt.Rows[i]["areaName"].ToString();
TreeNode AreaNode = new TreeNode(areaName);
SqlCommand cmd2 = cnn.CreateCommand();
cmd2.CommandText = "SELECT streetId, streetName FROM street WHERE areaId = @areaId";
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.AddWithValue("@areaId", areaID);
SqlDataAdapter sdr2 = new SqlDataAdapter(cmd2);
cmd2.Connection = cnn;
sdr2.Fill(dt2);
for (int j = 0; j < dt2.Rows.Count; j++)
{
// Current StreetName and StreetId is stored
string streetId = dt2.Rows[j]["streetId"].ToString();
string streetName = dt2.Rows[j]["streetName"].ToString();
// A TreeNode is created with current StreetName
TreeNode StreetNode = new TreeNode(streetName);
// Current StreetNode is added as child node of AreaNode
AreaNode.Nodes.Add(StreetNode);
}
treeView1.Nodes.Add(AreaNode);
}
}
请我帮忙。
答案 0 :(得分:0)
我找到了我的解决方案,我在其间插入了dt2.Clear(),它正常工作
cmd2.Connection = cnn;
dt2.Clear();
sdr2.Fill(dt2);