Wednesday, 30 March 2011

Binding Treeview Dynamically in Asp.Net


Binding Treeview Dynamically in Asp.Net

Download
ExtendedTreeView.dll file from below link

You will need to add its reference to your project in the following way.
Right click on the ajax extension in toolbox select choose item option then select browse option
Then select downloaded dll file. Then prees ok. Xtreeview added in ur toolbox


.
I’m using session Session["cls"].ToString(); for classid after login.

Implementation

Html Code

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="treeview.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="ExtendedTreeView" namespace="ExtendedControls" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table class="style1">
            <tr>
                <td  valign="top">
       <cc1:XTreeView ID="XTreeView1" runat="server"
                        onselectednodechanged="XTreeView1_SelectedNodeChanged">
    </cc1:XTreeView>

         
                </td>
                <td valign="top">
                       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                        CellPadding="4" ForeColor="#333333" GridLines="None" Width="831px">
                        <RowStyle BackColor="#E3EAEB" />
                        <Columns>
                            <asp:TemplateField HeaderText="Topics">
                            <ItemTemplate>
                           
                           <%--<a href='students_Subjectperformance.aspx?topicid=<%#Eval("id") %>' ><asp:Label ID="Label1" runat="server" Text='<%# Eval("topic") %>'></asp:Label></a>--%>
 
                            <%--<a href='mcqans.aspx?topicid=<%#Eval("id") %>' ><asp:Label ID="Label1" runat="server" Text='<%# Eval("topic") %>'></asp:Label></a> --%>
                          <a href='videoplay.aspx?topicid=<%#Eval("id") %>' ><asp:Label ID="Label1" runat="server" Text='<%# Eval("topic") %>'></asp:Label></a>
                          <%--<a href='askquestion_by_student.aspx?topicid=<%#Eval("id") %>' ><asp:Label ID="Label2" runat="server" Text='<%# Eval("topic") %>'></asp:Label></a>--%>
                           
                           </ItemTemplate>
                            </asp:TemplateField>
                   <%--      <asp:TemplateField HeaderText="Ask Question">
                            <ItemTemplate>
                              <a href='mcqans.aspx?topicid=<%#Eval("id") %>' ><asp:Label ID="Label1" runat="server" Text='<%# Eval("topic") %>'></asp:Label></a>
                                 <a href='askquestion.aspx?topicid=<%#Eval("id") %>' ><asp:Label ID="Label2" runat="server" Text="Ask Question"></asp:Label></a>
                           
                           </ItemTemplate>
                            </asp:TemplateField>--%>
                        </Columns>
                   
                    
                        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"
                            HorizontalAlign="Left" />
                        <EditRowStyle BackColor="#7C6F57" />
                        <AlternatingRowStyle BackColor="White" />
                   
                   
                    </asp:GridView>
                </td>
            </tr>
            <tr>
                <td>
                   </td>
                <td>
                  </td>
            </tr>
        </table>

         
    </div>

    </form>
</body>
</html>

C# code
using System;
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Threading;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();
    SqlDataAdapter adp = new SqlDataAdapter();
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
            con.Open();

  // binding root node
            SqlDataAdapter adapter = new SqlDataAdapter("select * from tbClasses where id=@id --where terms=1   --select distinct termid from tbSubjects", con);
            adapter.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = Session["cls"].ToString();
            DataTable parentTable = new DataTable("tbClasses");

            adapter.Fill(parentTable);
            ds.Tables.Add(parentTable);
  // binding sub menu in  the  root node
            adapter = new SqlDataAdapter("select * from tbTerms where classid=@classid --where --classid=23", con);
            adapter.SelectCommand.Parameters.Add("@classid", SqlDbType.Int).Value = Session["cls"].ToString();
            DataTable childTable = new DataTable("tbTerms");

            adapter.Fill(childTable);
            ds.Tables.Add(childTable);
// binding sub menu in  the sub menu of the   root node
            adapter = new SqlDataAdapter(@"select tbSubjects.*,tbTerms.classid from tbSubjects
            inner join tbTerms on  tbTerms.id=tbSubjects.termid
            where tbTerms.classid=@classid --select * from tbSubjects --where classid=23", con);
            adapter.SelectCommand.Parameters.Add("@classid", SqlDbType.Int).Value = Session["cls"].ToString();
            DataTable gchildTable = new DataTable("tbSubjects");
       // you can extend in accoring to ur need
            adapter.Fill(gchildTable);
            ds.Tables.Add(gchildTable);


            XTreeView1.ParentChildRealtionField = "id";
            XTreeView1.ParentNodeTextField = "class";


            XTreeView1.ChildParentRelationField = "classid";
            XTreeView1.ChildNodeTextField = "terms";


            XTreeView1.ChildGrandChildRelationField = "id";
            XTreeView1.GrandChildRelationField = "termid";
            XTreeView1.GrandChildNodeTextField = "subjects";

            XTreeView1.DataSet = ds;

            XTreeView1.ExpandAll();


        }
    }
    protected void XTreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        Int32 i;
        i = Convert.ToInt32(XTreeView1.SelectedValue);
        adp = new SqlDataAdapter("select * from tbtopics where subjectid='" + i + "'", ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
        adp.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}
Database Script for tables


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbClasses]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tbClasses](
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [class] [varchar](50) NOT NULL,
 CONSTRAINT [PK_tbClasses_1] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbTerms]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tbTerms](
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [classid] [bigint] NULL,
      [terms] [varchar](50) NULL,
 CONSTRAINT [PK_tbTerms] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbSubjects]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tbSubjects](
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [termid] [bigint] NULL,
      [subjects] [varchar](100) NOT NULL,
 CONSTRAINT [PK_tbSubjects] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbTopics]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tbTopics](
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [subjectid] [bigint] NOT NULL,
      [topic] [varchar](250) NOT NULL,
 CONSTRAINT [PK_tbTopics] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tbTerms_tbClasses1]') AND parent_object_id = OBJECT_ID(N'[dbo].[tbTerms]'))
ALTER TABLE [dbo].[tbTerms]  WITH CHECK ADD  CONSTRAINT [FK_tbTerms_tbClasses1] FOREIGN KEY([classid])
REFERENCES [dbo].[tbClasses] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbTerms] CHECK CONSTRAINT [FK_tbTerms_tbClasses1]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tbSubjects_tbTerms1]') AND parent_object_id = OBJECT_ID(N'[dbo].[tbSubjects]'))
ALTER TABLE [dbo].[tbSubjects]  WITH CHECK ADD  CONSTRAINT [FK_tbSubjects_tbTerms1] FOREIGN KEY([termid])
REFERENCES [dbo].[tbTerms] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbSubjects] CHECK CONSTRAINT [FK_tbSubjects_tbTerms1]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tbTopics_tbSubjects1]') AND parent_object_id = OBJECT_ID(N'[dbo].[tbTopics]'))
ALTER TABLE [dbo].[tbTopics]  WITH CHECK ADD  CONSTRAINT [FK_tbTopics_tbSubjects1] FOREIGN KEY([subjectid])
REFERENCES [dbo].[tbSubjects] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tbTopics] CHECK CONSTRAINT [FK_tbTopics_tbSubjects1]



3 comments: