Adding Parent and Child Nodes in TreeView from Sql Server 2008

不打扰是莪最后的温柔 提交于 2019-12-11 01:01:12

问题


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"

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);
        }
    }

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


回答1:


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);

And then

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
     }
}


来源:https://stackoverflow.com/questions/7640376/adding-parent-and-child-nodes-in-treeview-from-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!