<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dotnet thoughts &#187; Common Table Expressions</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/common-table-expressions/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>a dotnet developer&#039;s technical blog</description>
	<lastBuildDate>Wed, 08 Feb 2012 03:18:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>TreeView Population without recursive function</title>
		<link>http://www.dotnetthoughts.net/2009/10/20/treeview-population-without-recursive-function/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/20/treeview-population-without-recursive-function/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 14:42:56 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Common Table Expressions]]></category>
		<category><![CDATA[CTE]]></category>
		<category><![CDATA[Recursive function]]></category>
		<category><![CDATA[Treeview]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=544</guid>
		<description><![CDATA[If you want to display hierarchical data in a Treeview normally we are using recursion. I was looking for code which helps to avoid recursion using a Single query. But that code was using VB.Net and it was using a &#8230; <a href="http://www.dotnetthoughts.net/2009/10/20/treeview-population-without-recursive-function/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you want to display hierarchical data in a Treeview normally we are using recursion. I was looking for code which helps to avoid recursion using a Single query. But that code was using VB.Net and it was using a class called &#8220;Collection&#8221;, which is not available in C#. So I was looking for a compatable code in C# for long time and today I got the chance to re-write it using C#, but I am using Lamda expressions for this.</p>
<p>Here is the Table structure I want to display in Treeview</p>
<pre class="brush: sql; title: ; notranslate">

CREATE TABLE [dbo].[tblEmployees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [nvarchar](50) NOT NULL,
[Parent] [int] NOT NULL)
</pre>
<p>And I inserted following Data in it.</p>
<div id="attachment_545" class="wp-caption alignnone" style="width: 299px"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2009/10/Table_Data.JPG" alt="Table Data" title="Table Data" width="289" height="383" class="size-full wp-image-545" /><p class="wp-caption-text">Table Data</p></div>
<p>And the Stored Procedure for getting employees using Common Table Expressions.</p>
<pre class="brush: sql; title: ; notranslate">
-- usp_GetEmployees
CREATE PROCEDURE [dbo].[usp_GetEmployees]
AS
BEGIN
	WITH SimpleRecursive AS
	(SELECT EmployeeName, EmployeeId, Parent, 0 AS Depth FROM dbo.tblEmployees
	WHERE (EmployeeId IN(SELECT EmployeeId FROM dbo.tblEmployees AS Recursion1
	WHERE (Parent = 0)))
	UNION ALL
	SELECT P.EmployeeName, P.EmployeeId,P.Parent, A.Depth + 1 AS Depth
	FROM dbo.tblEmployees AS P INNER JOIN SimpleRecursive AS A ON A.EmployeeId = P.Parent)
	SELECT EmployeeName, EmployeeId, CONVERT(INT, Parent) AS Parent, Depth
	FROM SimpleRecursive AS SimpleRecursive_1
	ORDER BY Depth
END
</pre>
<p>And the code in C# which adding nodes to Treeview.</p>
<pre class="brush: csharp; title: ; notranslate">
private void PopulateTreeview()
{
    this.tvEmployees.Nodes.Clear();
    Employees employees = new Employees();
    using (SqlConnection connection = new SqlConnection(@&quot;Server=.\SQLEXPRESS; User Id=SQLUser;Password=SQLPassword;Database=Database&quot;))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(&quot;usp_GetEmployees&quot;, connection))
        {
            command.CommandType = System.Data.CommandType.StoredProcedure;
            SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                employees.Add(new Employees.Employee()
                {
                    Depth = int.Parse(reader[&quot;depth&quot;].ToString()),
                    EmployeeId = int.Parse(reader[&quot;EmployeeId&quot;].ToString()),
                    Parent = int.Parse(reader[&quot;Parent&quot;].ToString()),
                    EmployeeName = reader[&quot;EmployeeName&quot;].ToString(),
                });
            }
        }
    }

    foreach (Employees.Employee employee in employees)
    {
        Employees.Employee parentEmp = employees.Find(o =&gt; o.EmployeeId == employee.Parent);
        if (parentEmp != null)
        {
            this.tvEmployees.Nodes.Find(parentEmp.EmployeeId.ToString(), true)[0].Nodes.Add(employee.EmployeeId.ToString(), employee.EmployeeName);
        }
        else
        {
            this.tvEmployees.Nodes.Add(employee.EmployeeId.ToString(), employee.EmployeeName);
        }
    }
    this.tvEmployees.ExpandAll();
}
</pre>
<p>And the employees class </p>
<pre class="brush: csharp; title: ; notranslate">
public class Employees : List&lt;Employees.Employee&gt;
{
    public class Employee
    {
        public int EmployeeId
        {
            get;
            set;
        }
        public string EmployeeName
        {
            get;
            set;
        }
        public int Parent
        {
            get;
            set;
        }
        public int Depth
        {
            get;
            set;
        }
    }
}
</pre>
<p>And here is the screenshot</p>
<p><div id="attachment_551" class="wp-caption alignnone" style="width: 345px"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2009/10/treeview_Demo.JPG" alt="Treeview Demo - Screenshot" title="Treeview Demo - Screenshot" width="335" height="447" class="size-full wp-image-551" /><p class="wp-caption-text">Treeview Demo - Screenshot</p></div><br />
Thanks to <strong>Aneesh</strong> and <strong>Anas</strong> for their valuable comments.<br />
Happy Programming <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="betterrelated"><p><strong>Related content:</strong></p>
<ol><li> <a href="http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/" title="Permanent link to How to Store and Retrieve files from SQL Server Database">How to Store and Retrieve files from SQL Server Database</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/" title="Permanent link to Implementing Custom Paging in DataRepeater using C# and SQL Server">Implementing Custom Paging in DataRepeater using C# and SQL Server</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/" title="Permanent link to Adding and Reading files from SQL Server 2008 Filestream">Adding and Reading files from SQL Server 2008 Filestream</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/07/06/filestream-in-sql-server-2008/" title="Permanent link to FILESTREAM in SQL Server 2008">FILESTREAM in SQL Server 2008</a>  </li>
<li> <a href="http://www.dotnetthoughts.net/2009/07/04/drag-and-drop-files-from-windows-to-your-application/" title="Permanent link to Drag and Drop files from Windows to your application">Drag and Drop files from Windows to your application</a>  </li>
</ol></div>]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/20/treeview-population-without-recursive-function/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

