Domanda

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.

È stato utile?

Soluzione

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
     }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top