我有树视图:
<asp:TreeView ID="testtree1" runat="server" OnSelectedNodeChanged="testtree1_SelectedNodeChanged">
<Nodes>
<asp:TreeNode Expanded="False" Text="Tests" Value="Tests"></asp:TreeNode>
</Nodes>
</asp:TreeView>
我在我的.cs文件中有这段代码:
protected void testtree1_SelectedNodeChanged(object sender, EventArgs e)
{
if (testtree1.SelectedNode.Text == "Tests")
{
con.Open();
SqlCommand cmdd = new SqlCommand("select count(Name) from TypeOfWork");
cmdd.Connection = con;
int idcount = Convert.ToInt32(cmdd.ExecuteScalar());
SqlCommand cmd = new SqlCommand("select Name from TypeOfWork");
cmd.Connection = con;
string[] nid = new string[idcount];
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < idcount; i++)
{
nid[i] = ds.Tables[0].Rows[i]["Name"].ToString().Trim();
testtree1.Nodes.Add(new TreeNode(nid[i]));
}
}
}
else
{
string tstr = testtree1.SelectedNode.Text;
con.Open();
SqlCommand cmd = new SqlCommand("select TypeOfWorkID from TypeOfWork where Name='" + tstr + "'");
cmd.Connection = con;
int tid = Convert.ToInt32(cmd.ExecuteScalar());
SqlCommand cmdd = new SqlCommand("select count(Name) from CategoryLevel1 where TypeOfWorkID='" + tid + "'");
cmdd.Connection = con;
int idcount = Convert.ToInt32(cmdd.ExecuteScalar());
SqlCommand cmd1 = new SqlCommand("select Name from CategoryLevel1 where TypeOfWorkID='" + tid + "'");
cmd1.Connection = con;
string[] nid = new string[idcount];
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < idcount; i++)
{
nid[i] = ds.Tables[0].Rows[i]["Name"].ToString().Trim();
TreeNode child1 = new TreeNode();
child1.Text = nid[i];
testtree1.Nodes.Add(child1);
}
}
}
}
这里的问题是我得到一棵树获取正确的数据,但没有得到应该的树视图。
根点Tests
当我点击它时我得到Civil
和RVI
但是它们不是tests
当我点击Civil
或RVI
时,它的子节点不仅仅是普通的树,而是在做什么?
任何帮助
答案 0 :(得分:1)
您需要添加到当前所选节点的childNodes集合,而不是添加到根节点:
protected void testtree1_SelectedNodeChanged(object sender, EventArgs e)
{
var selectedNode = (sender as System.Web.UI.WebControls.TreeView).SelectedNode;
selectedNode.ChildNodes.Add(new TreeNode('Your TreeNode here'));
}
代码中的,而不是:
testtree1.Nodes.Add(new TreeNode(nid[i]));
使用:
(sender as System.Web.UI.WebControls.TreeView).SelectedNode.ChildNodes.Add(new TreeNode(nid[i]));