I'm getting an "Object reference not set to an instance of an object" error with this line of code:

t1.FindNode(rs.GetString(4)).ChildNodes.Add(node);

Here is all of the code:

using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

namespace TreeViewProject
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            PopulateTree(SampleTreeView);

        }



        public void PopulateTree(TreeView t1)
        {

            // Clear any exisiting nodes
            t1.Nodes.Clear();

            using (SqlConnection connection = new SqlConnection())
            {
                // Data Connection
                connection.ConnectionString = (ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
                connection.Open(); 

                string getLocations = @"
                    With hierarchy (id, [location id], name, depth, [path])
                    As (

                        Select ID, [LocationID], Name, 1 As depth,
                            Cast(Null as varChar(max)) As [path]
                        From dbo.Locations
                        Where ID = [LocationID]

                        Union All

                        Select child.id, child.[LocationID], child.name,
                            parent.depth + 1 As depth,
                            IsNull(
                                parent.[path] + '/' + Cast(parent.id As varChar(max)),
                                Cast(parent.id As varChar(max))
                            ) As [path]
                        From dbo.Locations As child
                        Inner Join hierarchy As parent
                            On child.[LocationID] = parent.ID
                        Where child.ID != parent.[Location ID])

                    Select *
                    From hierarchy
                    Order By [depth] Asc";

                using (SqlCommand cmd = new SqlCommand(getLocations, connection))
                {
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataReader rs = cmd.ExecuteReader())
                    {
                        while (rs.Read())
                        {
                            Guid id = rs.GetGuid(0);
                            Guid locationID = rs.GetGuid(1);
                            TreeNode node = new TreeNode();
                            node.Text = rs.GetString(2);
                            node.Value = id.ToString();
                            

                            if (id == locationID)
                            {
                                t1.Nodes.Add(node);
                            }
                            else
                            {
                                t1.FindNode(rs.GetString(4)).ChildNodes.Add(node); 
                                
                            }
                        }
                    }
                }
            }
        }

    }
}

Any help would be appreciated.

Dani AI

Generated

Good concise troubleshooting and resolution by and — the exception happened because a lookup returned no node and the code dereferenced it. Below are practical, defensive patterns and a couple of alternative approaches to make tree-building robust and easier to debug.

Checklist and quick fixes

  • Always validate reader fields before using them (check for DBNull and trim the string).
  • Never call a method on the return of a lookup without checking for null first. Example pattern:
var parent = myTree.FindNode(parentPath);
if (parent != null)
{
    parent.ChildNodes.Add(childNode);
}
else
{
    // log or collect the missing parentPath for inspection
}

Safer lookups and performance

  • If you need to find nodes by Value (ID) rather than by a value path, use the collection search or maintain an index. Building a Dictionary keyed by node.Value gives O(1) parent lookup and works well for large result sets:
var index = new Dictionary<string, TreeNode>(StringComparer.OrdinalIgnoreCase);
// when creating nodes: index[node.Value] = node;
// to attach: if (index.TryGetValue(parentId, out var parent)) parent.ChildNodes.Add(node);

Extra tips

  • Prefer culture-invariant comparisons (e.g., StringComparer.OrdinalIgnoreCase or ToLowerInvariant) over plain ToLower to avoid locale surprises.
  • Log any missing parents (include the raw value and trimmed value) so you can quickly see data problems.
  • If the value you pass to FindNode is actually a path, confirm it uses the same separators and casing as ValuePath.

These patterns prevent null-reference exceptions, improve debuggability, and scale better than repeated tree traversal. — thread resolution is appropriate once you’ve verified these checks.

Recommended Answers

All 3 Replies

your code: t1.FindNode(rs.GetString(4)).ChildNodes.Add(node);

rs.getstring(4) might be null therefore triggering that exception, OR else tl does not contain the node whose name is from result rs.GetString()\

Check them both starting from rs.GetString(4) - ensure its not null.. by placing a breakpoint, and using immediate window for debugging

Turns out it was grabbing GetString(4) as an uppercase, so it couldn't find a match. Adding ToLower() fixed the issue. Thanks for your help!

MArk this thread as solved you issue is fixed

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.