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]



21 comments:

  1. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training in chennai velachery | dot net training institute in velachery

    ReplyDelete
  2. I really like the dear information you offer in your articles. I’m able to bookmark your site and show the kids check out up here generally. Im fairly positive theyre likely to be informed a great deal of new stuff here than anyone
    Click here:
    angularjs training in sholinganallur
    Click here:
    angularjs training in btm

    ReplyDelete
  3. Great content thanks for sharing this informative blog which provided me technical information keep posting.
    Blueprism training in Chennai

    Blueprism training in Bangalore

    Blueprism training in Pune

    Blueprism online training

    ReplyDelete
  4. Awesome..You have clearly explained …Its very useful for me to know about new things..Keep on blogging..
    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    ReplyDelete
  5. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command

    Data Science Training in Chennai | Data Science training in anna nagar
    Data Science training in chennai | Data science training in Bangalore
    Data Science training in marathahalli | Data Science training in btm

    ReplyDelete
  6. Tökezlediğiniz ve ayağa kalkıp(  taxi Nội Bài ) devam edemediğiniz gibi görünen zamanlar vardır, lütfen bazen( taxi sân bay nội bài rẻ nhất )  zorlukların üstesinden gelmenize yardımcı olacak, yaşamınızla(số điện thoại taxi nội bài ) ilgili iyi ( taxi nội bài - Hoàn kiếm ) et. Aşağıdaki makale, yaşam hakkında 100'den fazla güzel kelime size tanıtır.

    ReplyDelete
  7. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Visit us: dot net training
    Visit us: Dot Net Online Training Hyderabad
    Visit us: .net online training india
    Visit us: Dot Net Training Online India
    Visit us: .Net Online Training Hyderabad
    Visit us: Dot Net Online Training
    Visit us: Dot Net Online Course
    Visit us: .Net Online Training

    ReplyDelete
  8. Thanks a lot. You have done an excellent job. I enjoyed your blog . Nice efforts.
    Visit us: Dot Net Training Online India
    Visit us: .Net Online Training Hyderabad

    ReplyDelete
  9. I don t have the time at the moment to fully read your site but I have bookmarked it and also add your RSS feeds. I will be back in a day or two. thanks for a great site. World Market Link

    ReplyDelete