views:

1101

answers:

2

I am accustomed to winform TreeView having a Sorted property which automatically manages nodes sorting. I now have to alphabetically sort an ASP.NET TreeView and I'm surprised I cannot find any similar property or callback method.

Is there any way to automatically achieve this operation in ASP.NET or do I have to manually sort and insert my nodes in correct order?

+1  A: 

You'll need to write your own sorting function but its reasonably trivial to add this functionality.

http://blog.mdk-photo.com/post/C-Extentionmethod-Tree-Node-View-Sort().aspx

.NET 3.5 supports extension methods so you can add functionality to pre-existing System Classes. Notice the this syntax on the method parameter. More Info Here

public static void Sort(this TreeView tv)
{
    TreeNodeCollection T = tv.Nodes.Sort();
    tv.Nodes.Clear();
    tv.Nodes.AddRange(T);
}

public static void Sort(this TreeNode tn)
{
    TreeNodeCollection T = tn.ChildNodes.Sort();
    tn.ChildNodes.Clear();
    tn.ChildNodes.AddRange(T);
}

The first link contains the rest of the code you'll need to complete the sorting functionality

Eoin Campbell
I know extension methods but I prefer building my own control inheriting from TreeView and implementing the new feature.Otherwise, your link provides a full detailed solution so I'll accept your anwer if I don't receive others in a few time :)
Tyalis
One issue is that this solution does not persist the selected node due to the `tv.Nodes.Clear();` call. Store the ValuePath of the selected node to re-select it once the sort is complete.
JHappoldt
A: 

try { trv_JobNo.Nodes.Clear();

        foreach (DataRow dr in dt.Rows)
        {
            TreeNode tr = new TreeNode();
            tr.Value = dr["JobNo"].ToString();
            DataTable dt_RFI = new DataTable();
            string sJobNo = dr["JobNo"].ToString();
            adp = new SqlDataAdapter("Select * from tbl_RFI where JobNo like '" + @sJobNo + "%'", connPO);
            adp.Fill(dt_RFI);

            foreach (DataRow dr_RFI in dt_RFI.Rows)
            {
                TreeNode tr_RFI = new TreeNode(dr_RFI["RFINo"].ToString());
                tr_RFI.Value = dr_RFI["RFINo"].ToString();
                tr.ChildNodes.Add(tr_RFI);
            }
            trv_JobNo.Nodes.Add(tr);                               
        }            
    }

My treeview has been binding like this... how can i sort?

CMMaung
Your tree isn't really databound, it is manually filled so you can use Eoin's solution.
Tyalis