添加在树视图父和子节点从SQL Server 2008 [英] Adding Parent and Child Nodes in TreeView from Sql Server 2008

查看:159
本文介绍了添加在树视图父和子节点从SQL Server 2008的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对家长和孩子节点添加从SQL Server到树视图。我实现了一些code。但我得到的错误索引超出范围

i want to add the parent and child nodes from sql server to treeview. i implemented some code. but i gets error "Index was out of range"

下面是code我使用,以填补父和子节点。

below is the code i am using to fill parent and child nodes.

protected void GetParentNodes()
    {
        SqlDataAdapter adap = new SqlDataAdapter("select id, name from crossarticle_category where parentid=-1", con);
        DataTable dt = new DataTable();
        adap.Fill(dt);
        int index = -1;
        foreach (DataRow d in dt.Rows)
        {
            SqlDataAdapter adapInner = new SqlDataAdapter("select id, name from crossarticle_category where parentid=" + Convert.ToInt32(d["id"].ToString()) + "", con);
            DataTable dtInner = new DataTable();
            adapInner.Fill(dtInner);
            index++;
            TreeNode n = new TreeNode();
            n.Value = d["id"].ToString();
            n.Text = d["name"].ToString();
            foreach (DataRow r in dtInner.Rows)
            {
                if (dtInner.Rows.Count > 0)
                {
                    TreeNode inner = new TreeNode();
                    inner.Value = r["id"].ToString();
                    inner.Text = r["name"].ToString();
                    tree1.Nodes[index].ChildNodes.Add(inner);
                }
            }
            tree1.Nodes.Add(n);
        }
    }

谁能帮助我纠正这个问题在这个code ..这code已经被自己创建的。

can anyone help me rectify the issue in this code.. this code has been created by myself.

推荐答案

看起来你尝试添加一个子节点添加父面前。第一次尝试,然后添加父子节点;像这样:

Looks like you are trying to add a child node before you add the parent. Try adding the parent first and then the child nodes; like so:

///...

n.Value = d["id"].ToString();
n.Text = d["name"].ToString();

tree1.Nodes.Add(n);

然后

foreach (DataRow r in dtInner.Rows)
{
    if (dtInner.Rows.Count > 0)
    {
        TreeNode inner = new TreeNode();
        inner.Value = r["id"].ToString();
        inner.Text = r["name"].ToString();
        tree1.Nodes[index].ChildNodes.Add(inner); //node at pos index should exist now
     }
}

这篇关于添加在树视图父和子节点从SQL Server 2008的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆