Ralph Varjabedian
Coding is a systematic art

Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Tuesday, April 22, 2008 10:17 PM

UPDATE: (14/10/2008) Thank you for everybody who has commented on this post and given me valuable feedbacks.

I have updated the C# code to include most of your comments/fixes. 

Includes: Proper handling for null or empty column values as the parent columns and added subtree loading.

Thank you again.

 

The other day I wanted to bind a TreeView to a DataSet (or an ObjectDataSource that would return a DataSet) and I was disappointed to see that it does not support this. Googling this showed a lot of developers opting to fill the TreeView themselves programmatically. So I decided to create a simpler solution for this.

The key to this solution is that the TreeView can bind to any object that implements the interface IHierarchicalDataSource. So I created a simple class that takes a DataSet as its input along with two column names, I will explain them in a moment, and this class would implement the IHierarchicalDataSource interface.

So instead of writing:

TreeView1.DataSource = dataSet;

which is not supported, we write this:

TreeView1.DataSource = new HierarchicalDataSet(dataSet, "ID", "ParentID");

Check this post for the VB.NET version of the sample application.

The two extra parameters that you have to pass to the constructor of HierarchicalDataSet are two column names. The first one being the primary key of the table, and the second one being the parent key which usually would be a foreign key to the primary key of the same table; this allows modeling the tree structure in a database table. Here is a simple design of such a table.

Table design for a tree structure

 

 











Feedback

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

This is what I was looking for - our org chart is represented in an oracle table with columns employee_number, supervisor_emp_number, and I need to use something like a treeView control to display it on our Intranet. You're right, everyone seems to be building the hierarchical part on the fly, which can consume resources.

Thanks for posting this! 4/24/2008 11:30 PM | Paulette Neal-Allen

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

You're welcome. Please do not hesitate to let me know if you need anything else. 4/26/2008 11:02 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,
this is very interesting indeed, thank you for that.

For less experienced readers, I would indicate that the TreeView DataBindings needs to be setup appropriately.

This can be done in several ways:
A) by inserting bindings definition in the asp:TreeView tag:
<DataBindings>
<asp:TreeNodeBinding
DataMember="System.Data.DataRowView"
TextField="Text"
ValueField="ID" />
</DataBindings>

B) or with code like this:
//---
TreeNodeBinding tnb = new TreeNodeBinding();
tnb.DataMember = "System.Data.DataRowView";
tnb.TextField = "Text";
tnb.ValueField = "ID";
tnb.PopulateOnDemand = false;
tnb.SelectAction = TreeNodeSelectAction.Select;
TreeViewPS.DataBindings.Add(tnb);

TreeViewPS.DataSource = new BindingTools.HierarchicalDataSet(dataSet, "ID", "ParentID");
TreeViewPS.DataBind();
//---

C) or with the dialog available via the DataBindings property of the TreeView in the Designer.

Regards. 5/3/2008 1:24 AM | Alain Deby

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Well, you are right for the Binding code, this is already done in the Sample application, but it is a good idea to mention it in detail on the post itself for the less experienced. Thank you. 5/3/2008 2:21 AM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I keep receiving the error:

"Cannot find column[ORG00379]"

when the DataBind method is executed. ORG00379 is the ID of the first record in the query. Example:

PARENTID ID TEXT
---------- ---- ------
ORG00379 ORG 1
ORG00001 ORG 2
ORG00001 ORG00003 ORG 2A
ORG00001 ORG00005 ORG 2B

I'm using ASP.NET 2.0 and I don't know what you're doing with Assembly. The only thing I'm using is the IHierarchialDataSet.cs file in my App_Code folder. I've removed the namespace. Do you have any idea what the error is referring to exactly?

Thanks! 5/6/2008 6:36 PM | Jon

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

<pre>
PARENTID ID TEXT
--------- ----- --------
ORG00379 ORG 1
ORG00001 ORG 2
ORG00001 ORG00003 ORG 2A
ORG00001 ORG00005 ORG 2B
</PRE> 5/6/2008 6:38 PM | Jon

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

(PARENTID, ID, TEXT)

( , "ORG00379", "ORG 1")
( , "ORG00001", "ORG 2")
( "ORG00001", "ORG00003", "ORG 2A" )
( "ORG00001", "ORG00005" "ORG 2B" )

Okay, it's formatted properly. 5/6/2008 6:41 PM | Jon

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I believe I fixed it. The errors were because of the format strings created for GetParentRow(), HasChildren() and HierarchicalEnumerable.GetEnumerator(). Where the format string is "{0} = {1}", it should actually be "{0} = '{1}'". The first variable is a column name, whereas the second one is a value in the column. If there aren't any apostrophes, then it's trying to find a column name named after the value in the column.

So it works now... as far as I know. .NET craps out on me when the page attempts to load (faulting application w3wp.exe).... that's something else that's totally my problem. 5/6/2008 7:44 PM | Jon

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph
I am trying to use your IHierarchicalDataSet.cs in my project and class that populates dataset
and i pass the dataset and ID and ParentID to IhierarchicalDatasource but i face problem in this line

IEnumerator i = hDataSet.dataSet.Tables[0].DefaultView.GetEnumerator();

saying check if it is going in infinite loop

i am using sample dataset which you used in dafault.aspx.cs

PLease kindly advice where it is going wrong as i need it urgent and am new to using IHierarchical datasource

Thanks 5/8/2008 2:06 PM | Paul

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Paul, I will contact you by email to help you out. 5/8/2008 3:24 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Jon,

I see your problem, this is because your primary keys are strings which is why they need the single quotes, I will update my code to detect this and correctly work it out.

If you need any further help let me know. 5/8/2008 3:27 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Jon,

I updated the code to take into account the columns of type strings.

Let me know if you need something else. 5/14/2008 11:46 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I have the same isue as Paul, above, that being that the supplied code invariably falls into a stack overflow. Even utilising the supplied same data. Any idea how to resolve this? And, yes, before you ask, I'm using .NET 2.0. Is this an issue with this version of the .NET framework?

Many Thanks 5/15/2008 11:45 AM | Andy Twiss

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Andy,

I will follow up your case by Email to help you.
Thanks. 5/15/2008 12:32 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I used the code and it runs without any error but the tree view doesn't appear 5/18/2008 4:06 AM | somen

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I think that you are missing something here Jon. You stated that the expression used in the filter containing this :
"{0} = {1}"
needs to be changed to :
"{0} = '{1}'".

I am not sure about that. The apostrophe is usually used when building an expression with a string variable whereas without, the variable is expected to be numeric.

Since this index key is numeric, it seems to me that the filter is correct without the apostophes.


5/18/2008 8:44 PM | Howard

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello Howard,

Yes you are right. The code does not always change it to the filter with the quotes. The code checks the type of the column name and if it is a string type, then the quotes are used, if it is not of string, then quotes are not used, covering both cases.
5/19/2008 12:54 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

So, I have taken your updated class (that distinguishes between strings and numbers), and have replaced the version that I had. It works fine with the same programmatic dataset, but I have not been able to modify the datasource to use my resultset.

If I may, here is the SQL, the treeview, and the call.

1)
sSQL = "select distinct EMP_SSN, TO_NUMBER(EMP_SSN) AS PARENT_KEY_NUMBER, TO_NUMBER(CHILD_KEY) AS CHILD_KEY_NUMBER, UPDATE_DATETIME, TRANSACTION_TYPE, RecCount FROM ( " & vbCrLf & _
" SELECT EMP_SSN, UPDATE_DATETIME, '1' || '000' || EMP_SSN AS CHILD_KEY, 'CUR' as TRANSACTION_TYPE, SUM(1) AS RecCount" & vbCrLf & _
" FROM(TDF_FID_SCF_CUR) " & vbCrLf & _
" GROUP BY EMP_SSN, UPDATE_DATETIME " & vbCrLf & _
"" & vbCrLf & _
"" & vbCrLf & _
" UNION ALL " & vbCrLf & _
"" & vbCrLf & _
"" & vbCrLf & _
" SELECT EMP_SSN, UPDATE_DATETIME, '2' || '000' || EMP_SSN AS CHILD_KEY, 'CUR' as TRANSACTION_TYPE, SUM(1) AS RecCount" & vbCrLf & _
" FROM(TDF_FID_SCF_CUR) " & vbCrLf & _
" GROUP BY EMP_SSN, UPDATE_DATETIME " & vbCrLf & _
"" & vbCrLf & _
"" & vbCrLf & _
" UNION ALL " & vbCrLf & _
"" & vbCrLf & _
"" & vbCrLf & _
" SELECT EMP_SSN, UPDATE_DATETIME, '3' || '000' || EMP_SSN AS CHILD_KEY, 'CUR' as TRANSACTION_TYPE, SUM(1) AS RecCount" & vbCrLf & _
" FROM(TDF_FID_SCF_CUR) " & vbCrLf & _
" GROUP BY EMP_SSN, UPDATE_DATETIME " & vbCrLf & _
"" & vbCrLf & _
") " & vbCrLf & _
"" & vbCrLf & _
"Where UPDATE_DATETIME>=trunc(sysdate-8,'DD') " & vbCrLf & _
"order by EMP_SSN, UPDATE_DATETIME, CHILD_KEY" & vbCrLf & _
"" & vbCrLf & _
""

2)
<asp:TreeView ID="MyTree" runat="server" ImageSet="WindowsHelp">

<DataBindings>
<asp:TreeNodeBinding DataMember="System.Data.DataRowView"
TextField="EMP_SSN" ValueField="PARENT_KEY_NUMBER" />
</DataBindings>

<ParentNodeStyle Font-Bold="False" />
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False"
HorizontalPadding="0px" VerticalPadding="0px" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black"
HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="1px" />
</asp:TreeView>

3)
ds = DBUtils.GetDataSet(sSQL)
Me.MyTree.DataSource = New TreeViewBinding.HierarchicalDataSet(ds, "CHILD_KEY_NUMBER", "PARENT_KEY_NUMBER")
Me.MyTree.DataBind()

Please note that I have ported the code to vb.net.

Thanks,
Howard
5/19/2008 8:51 PM | Howard

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph
I have used your HierarchicalDataSet.cs in my project but my page doesnt show up anything
I have SQL server database with table
menu_item_id,Parent_id,Menu_item,Link
I have created a class that returns a dataset
then i want to populate the tree with this dataset .I have already tested my class with a windows form and it populates the form correctly .
Now i want to create a treeview with this dataset
can you please help its urgent as my deadline is close
Please help
5/20/2008 3:00 AM | sanya

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello Sanya and Howard,

I will answer your questions via email.

Howard if you can share with us your VB.NET Code that would be great, send it to me and I will post it by itself and with reference to you.
5/20/2008 12:47 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I'm adding another node to the sample to make an existing node a parent but it doesn't display. Here's the added row:

row = dataSet.Tables[0].NewRow();
row["ID"] = 7;
row["ParentID"] = 6;
row["Text"] = "Child of Child 4";
dataSet.Tables[0].Rows.Add(row);

Any ideas?

Ken
6/1/2008 10:23 PM | Ken Cox

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Nevermind about my added row comment above...

I was inadvertently referencing the compiled code rather than my edited .cs file. Oops.

Ken
6/1/2008 10:30 PM | Ken Cox

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Glad to hear you got it to work.
Let me know if you need further help.
Have a good day. 6/2/2008 2:56 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

This is great for a 2 level tree view..

I recently came across a problem in which I needed a 3 level Treeview...

I posted a question on Experts-Exchange. Here is the link..

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_23488558.html

I would appreciate your advice. Many Thanks!
Josh 6/16/2008 6:55 PM | Joshua Couto

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi,

Looks to me like a straight forward solution with my class, Your key here would be: "SubOwnerID" and your parent key would be "OwnerID". Just load the whole table and feed it to the class. It should work unless there is something I am not seeing.

Just as a side note, the solution presented is not just 2 levels, it is n levels nested under each other as much as you want, all you have to have is the correct parent-child relationship.

Let me know if you need further help. 6/17/2008 11:29 AM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Greate Code
Exactly what i was looking for 6/21/2008 9:49 AM | Sushilkumar Pandey

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph

I'm having the same problem as sanya where nothing shows up.

On debugging the control comes into the HierarchicalDataSet constructor and nothing happens after that. The dataset sure has got data in it.

Any ideas what's going wrong

( Note: as there is no explicit call for any other method inside the HierarchicalDataSet constructor Is it supposed to call any method in
the interface IHierarchicalDataSource)

Thanks
RainManAlex
6/24/2008 12:06 PM | RainManAlex

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello,

Can you please show me your data quickly, or email me your project altogether so that I can debug your example. And no the constructor does not call anything, it just hands in the interface IHierarchicalDataSource, upon binding the treeView will start calling methods inside the class (via the interface methods).

Let me know. 6/24/2008 12:54 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello, I have same problem like Paul's (5/8/2008 2:06 PM | Paul, Infinity Loop...)
Can U email a solution for this problem, thanks
6/27/2008 6:09 PM | Alex Petrov

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

nice piece of work, congratulations! I've been searching the web for quite some time to find a good solution for this problem and evaluated various approaches to bind my organisational data. Your solution is fast and very reliable, thank you!

For others using it, some minor remarks may be helpful:
- The Treeview will display nothing, when the 'root' has an entry in the parent-column. This may be important to know when only a subtree is to be displayed
- I put the whole into a 'If Not Page.IsPostBack' condition, as the tree doesn't need to be re-read on every postback
- In the VB code (HierarchicalDataSet.vb, sub new), I made two minor changes, as my ID-Variables are always numerical:

dataSet.Tables(0).Columns(idColumnName).DataType = GetType(String)
Me.columnIsString = True

throws an exeception, as VB cannot evaluate the first line, it was changed into

If (dataSet.Tables(0).Columns(idColumnName).DataType Is GetType(String)) Then
Me.columnIsString = True
End If

The according change is to be made in the second 'sub new' as well (with dataview.table)

Thanks again

Holger

6/30/2008 4:46 PM | Holger

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Holger

Thank you for the feedback. Your remarks are appreciated. It is true that the tree will not display if someone is feeding the data of a subtree, I will try to modify the code when my time permits to support this case.

As for the VB code, thank you for the changes, I will try to add them to the code.

Thanks again. 6/30/2008 5:24 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Thanks a lot, very nice 7/5/2008 1:25 AM | m.sayed

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I got this to work fine using VS2005, but had issues in VS2008. Has anyone used this code in VS2008 (C#)? 7/10/2008 11:50 PM | Ryan

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Well yes. Ryan, The project I created is on VS2008. Could you please explain what sort of issues you were having.

Thanks. 7/11/2008 12:44 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi,

To get the tree view to populate, the 'top level' parentID must not be set / must be null.

I need to apply this to an existing project where the ParentID of the 'top level' elements is set to zero (rather than null).

How do I adjust the class to accept either null or 0 as the parentID value for the top level?

I could achieve it with some 'if then else' within the SQL query, but would like to understand how to adjust the existing class to do so.

Many thanks,

Bilf
7/27/2008 5:36 PM | Bilfwebb

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello Bilf,

Well, for now I will give you a quick fix and then I will update the code and post to make this easier for the future.

It is very simple:
You have a method called: GetEnumerator and inside of it you have this line of code:

String.Format("{0} is null", hDataSet.parentIdColumnName);

Now instead of having "{0} is null", replace it with "{0} = 0" and it should work.

Let me know.
Regards. 7/28/2008 1:07 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

Perfect! I have amended the filter arguement to read : "{0} is null OR {0} = 0"

Thank again,
Best,
Bilf

7/28/2008 6:42 PM | Bilfwebb

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Thanx You.. Perfect Docs 7/31/2008 9:53 AM | Turkey

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Dear Ralph,

This is great - thanks. It works fine.

Is there a clear way to set the start node? The main reason I want this is to not display the single root "home" on a hierarchal menu, but instead display the next level as the starting nodes.

I'll look through it myself, but just thought you may have already worked on this.

Regards,
Kev 8/6/2008 11:38 AM | Kev

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Kev,

No there isn't a direct way in the class. However I am going to post an update soon with a couple of additions so this will be one of them, for now you have this filter:

"{0} is null" which is an indication of the top level parents nodes. All you need to do is pass by the id of the starting node that you want and modify this filter to consider that:

"{0} = [TOP LEVEL ID]"
(pass it as a parameter and do not hardcode it, this is just for demonstration)

and you should be done.
Let me know if you need further help.
Regards. 8/6/2008 11:52 AM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Wow, what a fast reply! That worked great. All I need to do now is figure out the best way to pass the parameter from the instance into the static method. mmm... Any ideas here. Sorry to bother you again.
Cheers 8/6/2008 1:53 PM | Kev

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Just add it as a parameter to the constructor of HierarchicalDataSet class and let the compiler guide you through the errors to complete your implementation...

Let me know. 8/6/2008 4:10 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

Yes, I had a look at it like that already, but will have another try. I'll let you know how I get on.

Cheers,
Kev 8/6/2008 4:22 PM | Kev

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

I've still not got this going. I'm stuck as to how a parameter can be passed into the static method when the parameter relates to an instance of the outer class.

I did try finding my way through by adding a parameter into the outer constructor, but with no luck.

Cheers Again 8/11/2008 9:59 PM | Kev

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

Many thanks for this implementation. Saves a lot of work. However, it does not seems to work on one of my datsets. It gives me an System.StackOverflowException error on this line:

hDataSet.dataSet.Tables[0].DefaultView.RowFilter = String.Format("{0} = {1}", hDataSet.parentIdColumnName, lastID);

this is the binding:

this._TV.DataSource = new HierarchicalDataSet(retDS(), "ID", "ParentID");
this._TV.DataBind();

ID and ParentID are both type of int.

the visualiser on my website show my simple dataset. Would you know what I did wrong?

Many thanks,

Leo 8/11/2008 11:32 PM | leon

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Leon,

The problem is not with the code or the way you are using the code. The problem is with the data. The attached image that you have put, is this the data you are using? The rows that show an empty ParentID, are they null in the database (DBNull.Value in C#) or are they just empty. Moreover what is the field type of ParentID? is it int or string? Let me know so that I can help you better.

Regards. 8/12/2008 2:05 AM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Thanks for your quick response. That image is indeed the data I am using. Im creating a dataset on the fly and load it from xml values:

paramRes.Tables[0].Columns.Add("ID", typeof(int));
paramRes.Tables[0].Columns.Add("ParentID", typeof(int));

paramRes.Tables[0].PrimaryKey = new DataColumn[] { paramRes.Tables[0].Columns["ID"] };


This is how they get filled:
paramRes.Tables[0].Rows[i]["ID"] = i +1;
DataView dv = paramRes.Tables[0].DefaultView;
dv[i]["ParentID"] = int.Parse(parentID);

I also tried to put default dbnull values in the parentid column:
paramRes.Tables[0].Rows[i]["ParentID"] = DDBnull.value;

Many thanks Ralph.


8/12/2008 11:44 AM | Leo

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi,

Well I guess you need to debug it.
Here is what we can do.

1. Send me the DataSet schema you are using, you can send me the files of the DataSet, if it is not a typed dataset, please then try to create one typed.

2. In your application once you reach the place where you are about to bind the data. Use the dataset's method WriteToXML to export your data to an external xml file. Please send me this file wit h the typed data set and I will figure out the problem in no time...

Regards. 8/12/2008 12:11 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

Never mind my previous questions. I was using probably an old version and noticed the current download is updated. That one, with string type on the columns, worked!

Thanks! 8/12/2008 3:57 PM | Leo

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

hi ralph - this is really quite excellent.
i have a couple of constraints:

a) the tree is very large, so it can't be read into the client at one time. how would one modify this code to populate on demand?

b) when an item is modified, the icon of all its ancestors change. can the tree be updated without doing a rebind (since that will lose the expand structure)?

regards,
vivek 8/17/2008 8:08 PM | Vivek

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello,

I believe that the population in parts should be done at the Tree level, since my code simply delivers the data but does not control when or how. I will check it for you tomorrow.

As for b, Can you explain more about it. What you want is a way to change the icon of items without reloading? 8/17/2008 9:15 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

thanks, ralph.

for b) the important thing is that the tree not fold - the user's expanded nodes should be preserved, and any icon changes should appear "in-place". postbacks are ok.

appreciate the response.
vivek 8/17/2008 9:23 PM | Vivek

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Alright,

I will check this for you tomorrow and hope to have a solution.

Regards. 8/17/2008 9:32 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi,
I am worndering how to build a tree with a resultset in hand (what I mean by saying a result set is it is a DataTable)

I have a hirerachy like
ID, Name, ParentID

Some please suggest me how to bind the obtianed datatable to a treeview control

Thanks in advance
8/18/2008 3:29 PM | Kiran

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Kiran,

This is what the post is about.

Just use this line:

TreeView1.DataSource = new HierarchicalDataSet(dataTable.DefaultView, "ID", "ParentID");

Where the dataTable is your dataTable :)
8/18/2008 3:39 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

to follow up on my earlier question, it appears from the msdn documentation that
"HierarchicalDataSourceView does not currently support Insert, Update or Delete operations."

therefore, it appears that the technique in this article cannot be extended to auto-update when a node changes.

i wonder if you can suggest any workarounds? i suppose there's always the option of writing a lot of code to keep track of the updates, but it would be cool if there was an easier way to do this.

regards,
vivek 8/19/2008 6:53 PM | Vivek

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi, I have same problem like Paul's (5/8/2008 2:06 PM | Paul and Alex, Infinity Loop...)
Can U email a solution for this problem, thanks
8/27/2008 2:40 PM | Justin Markham

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello Justin,
Most probably your parent-child relationships are not correct. Can you please send me a sample of your data or if possible your code and I will take a look at it.
Regards. 8/27/2008 2:59 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,
The XML from the dataset is below. Just two rows causes the loop.

<NewDataSet>
<Table>
<NodeId>1936</NodeId>
<EnableSelect>true</EnableSelect>
<Title>Test</Title>
</Table>
<Table>
<NodeId>1938</NodeId>
<ParentNodeId>1936</ParentNodeId>
<EnableSelect>true</EnableSelect>
<Title>Test2</Title>
</Table>
</NewDataSet>

Cheers,
Justin. 8/27/2008 3:02 PM | Justin Markham

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Problem solved. required Framework 2.0 Sp1

8/27/2008 5:18 PM | justin Markham

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

hello, were you able to think of a way to perform auto-update with the adapter?
thanks! 9/2/2008 11:37 PM | vivek

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

So is it true that using this HierarchicalDataSet requires having at least .NET 2.0 SP1 installed? It works great on my DEV server (which has .NET 2.0 SP2), but it errors out on my QA server (which has .NET 2.0 but not sure of service packs, if any). I don't have the details of the error at this time. Do you have an updated version of this project that works without a need for SP1? 9/12/2008 3:34 AM | James

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I was not aware of this, I will try to run it on a machine without SP1 in the weekend and I will try to see if there are problems and fix them... Thanks for the info. 9/12/2008 12:18 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Did you find anything relating to problems on 2.0 Framework without SP1? I have the same problem as James. Works great in our development and test environments, but blows up in production and from what I can tell, SP1 is the difference in environments. 9/17/2008 8:08 PM | Ryan

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I didn't get to verify if my QA environment had any SPs or not, but since I don't have time to wait for solution, I ended up not using the HierarchicalDataSet class. I created a short and simple function that does the trick. Pretty quick and easy actually and it also supports post-retrieval sorting if you need to. Also, it doesn't use recursion so the performance is not bad at all. Here's the function prototype:

BindTreeView(TreeView tv, DataTable dt, string IDColumnName, string ParentIDColumnName, string textColumnName, string sortExpression) 9/19/2008 1:41 AM | James

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Love this control!

How would one go about auto populating the "NavigateUrlField" field in the binding? If I use bind the TreeView control to a SiteMapDataSource, I can set the "NavigateUrlField" field and the control knows how to navigate to the appropriate url.

Is this possible to set with this control? For example, can I add a column to the database that contains "url" and this pass this into the constructor of the class?

Thanks for the input,

Chris 10/27/2008 6:42 AM | Chris

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Chris,

I will look into this field and see if it can be done.

Cheers. 10/27/2008 12:17 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi, after thinking about this more, it's actually pretty simple. The problem was that I didn't have a column in my DataSet for the url. I added a column to my DataSet like follows: dataSet.Tables(0).Columns.Add("URL", GetType(String))

and then for the TreeView, I added the following syntax:

<DataBindings>
<asp:TreeNodeBinding DataMember="System.Data.DataRowView" TextField="Text" ValueField="ID" NavigateUrlField="URL" />
</DataBindings>

Everything is binding perfectly to the tree now.

Thanks again,

Chris 10/27/2008 2:55 PM | Chris

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Ralph,

How can I go about specifying how the TreeView will sort my data?

I'm using a tree control to display online spanish lessons. The lessons are grouped by the parent (i.e. Week 1-4 has lessons Greetings, More Greetings, Courtesy, tec. The 2nd group would be Week 5 - 8 that would have it's subsequent lesson details associated with this parent.

For my users who are a part of the program for any length of time, I want them to see the most recent group of lessons at the top of the tree and the older lessons down towards the bottom. I've got my data sorted correctly when it's loaded into the datatable, but when the tree is populated, it is showing the lowest parentid primary key and it's detail first in the list.

I will email the xml data in a separate email.

Thanks,


Chris

10/28/2008 5:41 AM | Chris

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Great. Thanks for sharing. 10/28/2008 10:35 AM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Try this.

Location the function:
public IEnumerator GetEnumerator()

There is a line in this function:
IEnumerator i = hDataSet.dataView.ToTable().DefaultView.GetEnumerator();

Just before this line, add this line:
hDataSet.dataView.Sort = "ID DESC";
Where ID is your actual column name...

Give it a try. 10/28/2008 10:46 AM | Ralph Varjabedian

# Guid DataBinding

I am not sure if this was addressed, but...
There is an issue if the ids used are Guids.
The fix is simple, add a guid Type check along with the string check:
columnIsString = dataView.Table.Columns[idColumnName].DataType == typeof(string) || dataView.Table.Columns[idColumnName].DataType == typeof(Guid);

This will need to be done in each constructor.

MTmace 11/18/2008 9:27 PM | MTmace

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Thanks for the info...
I will include it in the next update.
Best Regards. 11/19/2008 11:49 AM | Ralph Varjabedian

# Issues When Using New Overload 4th Parameter

Hi Ralph,

Thanks for the updated files.

I can get the new file to work ok as before, but when trying to use the new overload which includes rootParentColumnValue as the 4th param I get an exception. I am passing DBNull.Value as the fourth parameter as this is the parentID value of the root node.
Specifically, I get the error here:

Syntax error: Missing operand after '=' operator.

Line 229: {
Line 230: if (hDataSet.rootParentColumnValue != null)
Line 231: hDataSet.dataView.RowFilter = hDataSet.GetFilter(hDataSet.parentIdColumnName, hDataSet.rootParentColumnValue.ToString());
Line 232: else
Line 233: {

Can you help please?
Cheers. 11/28/2008 1:14 PM | Kevin

# Issues When Using New Overload 4th Parameter

Hi Ralph,

Sorry, I forgot to say that I also tried using the ID column value of the parent node instead of DBNull.Value. This created no exception, but also didn't start the tree below the root node - the root node was included in the tree. I'm examining the code again, but thought you might immediately know as you wrote it!

Regards 11/28/2008 1:20 PM | Kevin

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

It is true about the DBNull.Value. I will throw an exception, but why would u pass DBNull.Value, you are supposed to pass the value of the parent ID, for example if the node that you want it to start at has the ID of 142, then you pass the 142 to it. I just tried the project on my machine and it worked correctly. Can you tell me what exactly are you passing it? 11/28/2008 1:36 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

Sorry for wasting your time. I worked it out and it works fine now. The way I'd read the param name I was originally thinking that it was the parentID value of the parent node. Duh!

Thanks again - very useful.

Kevin 11/28/2008 2:06 PM | Kevin

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Kevin, No Problem at all. Glad you got it sorted out. If you have other topics you would like to see covered, please let me know. Have a nice day. 11/28/2008 10:35 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Great job. Thanks for the code 12/6/2008 3:58 PM | Avi

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

You're welcome. Glad my code helps fellow developers. 12/6/2008 4:19 PM | Ralph Varjabedian

# 3rd level of the tree

Hi Ralph,

Thanks for the class, it helped me lot. But i have a little problem;

I have a data like below:

Id ParentId Text
1 NULL Reporting
2 1 Report_Category_1
3 2 Report_1
4 2 Report_2

The problem is i can't see the Report_2 at the third level. Report_1 is ok, i can see it at the third level but Report_2 and the other reports with ParentId = 2 are not coming with dataset.
Can you help please?
Thanks
12/19/2008 11:06 AM | Kerim

# re: 3rd level of the tree

Ok Ralph,
I've solved my problem :)
Thanks again. 12/19/2008 2:08 PM | Kerim

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Glad, it is sorted out :), I am curious what was the problem? 12/20/2008 2:05 PM | Ralph Varjabedian

# ASP 2.0 SP1

Dear Ralph,

Thank you very much for this class it is really useful.

Regarding SP1: Indeed this class need SP1 installed to run properly othewise you will get lots of error messages.

Regards,

Mustafa 1/10/2009 12:05 PM | Mustafa

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I was going to update the code to fix this, but since my time is scare, I figured eventually SP1 will be installed :) Thanks for your comment. 1/12/2009 12:00 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Tanks and many thanks, i will study and apply. 1/12/2009 2:43 PM | Birtas Adrian Ioan

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

I'm having trouble getting the SelectableField working when using this. It works great otherwise.

I use this:

MenuItemBinding mib = new MenuItemBinding();

mib.DataMember = "System.Data.DataRowView";
mib.TextField = "Text";
mib.ValueField = "Path";
mib.SelectableField = "Selectable";

Menu1.DataBindings.Add(mib);

There is a field called "Selectable" in the DB.

Any ideas?

Cheers,
Kevin 1/18/2009 7:42 PM | Kev

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

Do you have any updated version with the changes discussed by users above.
I have run into a stack overflow error though it works perfectly fine on my dev system.
Am using framwork 2.0 and sql 2005

Cheers
Ivan 5/2/2009 8:41 AM | Igor

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi,
First of all, THANK YOU FOR THIS. IT IS GREAT.

How do I set when to expand or collapse the tree?
I want to click and expand on tree node, but when I click on the deepest node I want to have the possibility to select it and to do something with this selection.
Thank you very much for your help.

Ovidiu 5/19/2009 2:19 PM | Ovidiu

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Ivan, unfortunately I could not reproduce this on my system, can you please send me a sample application with this problem and I will try to figure this out, other than that, the only thing I can tell you is to have the latest update for .NET.

Regards. 5/19/2009 3:04 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Ovidiu,

You are welcome :)

When you override your Select event, just check if it has children or not, if it does not then it will be your deepest node. Does this answer your question? If not please let me know.

Regards.
5/19/2009 3:07 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Ralph,

Great work. Thank you for this. It saved a lot om my time.

Regards
Anish 6/3/2009 2:55 PM | Anish De

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

You are welcome, glad I could be of help. 6/9/2009 11:45 AM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello! Thanks for your tool.

I'm having the same problem as somen. The Treeview does not show. here's my code:

Data d = new Data();
GetBlogEntriesResult[] o = d.getBlogEntries().ToArray();
DataTable dt = new DataTable();
DataSet ds = new DataSet();

dt.Columns.Add("key", typeof(string));
dt.Columns.Add("Description", typeof(string));
dt.Columns.Add("Title", typeof(string));



foreach (GetBlogEntriesResult r in o)
{
DataRow row = dt.NewRow();
row["key"] = r.key;
row["Description"] = r.Description;
row["Title"] = r.Title;
}

ds.Tables.Add(dt);

this.tvEntryList.DataSource = new HierarchicalDataSet(ds, "key", "Description");
this.tvEntryList.DataBind();

**************************************

here's the table:
key Description Title
1 May Jem
2 June Mama's Family
3 June Space Harrier
4 July Erlend Øye
5 July Wait Till Your
6 July Cow and Chicken
7 August Dexter's Laboratory 8/21/2009 8:56 AM | sqeeb

# laptop tamiri

Thanks Good Share very Mach 8/23/2009 3:38 AM | mert kaan

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Quite inspiring,

This is a very interesting article,

It has come in very helpful,

Thanks for writing about it 10/26/2009 7:01 PM | web development

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I’ve never been so excited reading a blog as it touches me personally 12/3/2009 4:08 PM | kids with autism

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello I am quite new the web development and is assigned the task to publish the application to the outside world. The problem I currently have is the Treeview does not display the + and - nodes in IE but will display in FireFox on the production server. I have been fighting with it the last days but no luck. Any suggestions will be appreciated.

12/3/2009 9:30 PM | Calvin

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hello,

I can give you ideas that help you with the debugging and solving of such issues. Make a simple page, add the treeview to it, open it in IE and it will not show correctly. Now from IE, save the page as static HTML file (which would be the rendered control on the client side). Now open this HTML file again in visual studio, try to locate the problem by changing/modifying code in the HTML file and testing in IE until you solve the problem, once you understand what is causing the problem, go back to the asp.net treeview and try to override its render process to fix the bug.Also do not forget to make sure you have the latest asp.net updated as this problem might be resolved already, or google for fixes given by other developers.

Hope you solve it. 12/4/2009 12:15 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Hi Ralph,

I am still not sure why the static HTML files are different how it renders the control in IE and Firefox. 12/8/2009 7:11 AM | Calvin

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Calvin,

The process is not easy, modifying the HTML till u get it to work on IE... and then figuring out what do to with the control itself.

Did you try googling this problem?

Please specify an email when you reply so that I can contact you directly. The email will be only accessable to me.

Thanks. 12/8/2009 12:57 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I am like this post.the post is very nice. 12/12/2009 10:54 AM | LOUIS

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Great Post! It is always a great benefit to us to see how someone else is deploying MOSS! I wish that everyone would write posts like this so that we can learn more about how to deploy for all different size companies.
12/14/2009 2:19 PM | play online craps

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

As for the VB code, thank you for the changes, I will try to add them to the code.
12/21/2009 5:39 AM | Shared Web Hosting

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

I want to express my admiration of your writing skill and ability to make reader to read the while thing to the end. I would like to read more of your blogs and to share my thoughts with you. I will be your frequent visitor, that’s for sure. 12/21/2009 5:04 PM | php chat software

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Thank you for your support and encouragment. I wish I had more time to spare to write more posts, but I will try my best. Have a nice day. 12/22/2009 1:08 PM | Ralph Varjabedian

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

good job 12/25/2009 7:34 AM | nfl jerseys on sale

# re: Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

This is awesome! Thanks! 1/18/2010 5:24 PM | AndyV

Post a comment





 

Please add 2 and 7 and type the answer here: