Category Archives: XmlDataSource

[RESOLVED] How to display XML element content from the TreeView and Menu controls in an ASPX page

Below are an XML file, as the DataSource, and an aspx code with the TreeView and Menu controls.

Why the TreeView and Menu controls can not display the "1999" and "2000" for the <StarWars>
tag and <JurassicPark> tag?

XML file

<movies>
<
Adventure

>
<
StarWars>1999</StarWars>
<JurassicPark>2000</JurassicPark
>
<
IndependenceDay/></Adventure

>

<Animation

>
<IceAge
/><Shrek/></Animation>

<
Drama>
<
Titanic/><Ghost/><ForrestGump/></Drama>

<Horrer
>
<Jawa
/><TheRing/></Horrer><movies>

aspx code
<asp:TreeView id="CheckBoxList1" DataSourceId="srcMovies" Runat="server" />
<asp:Menu id="BulletedList1" DataSourceId="srcMovies" Runat="server" />

Hi,

wonjartran

Why the TreeView and Menu controls can not display the "1999" and "2000" for the <StarWars>
tag and <JurassicPark> tag?

You need to bind your treeview or menu control by InnerText.

Like:

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1" OnTreeNodeDataBound="TreeView1_TreeNodeDataBound">
            <DataBindings>
                <asp:TreeNodeBinding TextField="#InnerText" DataMember="StarWars" />
                <asp:TreeNodeBinding TextField="#InnerText" DataMember="JurassicPark" />
            </DataBindings>
        </asp:TreeView>

XmlDataSource is refered to your xml file.

Check this overview:

http://msdn.microsoft.com/en-us/library/494y92bs.aspx

Hope this can help you.

[RESOLVED] Bind TreeView to XML-DataType Column in SQL

Hi Guys,

I have a Table in SQL Database, it only has one sell and its xml type.

I need to bind that xml to TreeView Control, and since I can't bind use sqldatasource as a datasource for the treeview and i cant use the XmlDataSource to read from the database... whats the best solution.

Best Regards

Can you post sample xml, just to know the structure.

You can use a DataSet and load Dynamic XML data from Database to Dataset and then use this dataset as datasource to the TreeView control

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);            
    DataTableReader reader = this.GetDataReader();
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(reader.GetString(reader.GetOrdinal("XmlData")));
    DataSet ds = new DataSet();
    ds.ReadXml(new XmlNodeReader(doc));
    treeView.DataSource = ds;
    treeView.DataBind();            
}
protected DataTableReader GetDataReader()
{
    ///
    /// Get data reader here
    /// 
}  

This is the structure :

 

<Accounts>
  <ParentAccount name="Asset" id="123">
    <ChildAccount name ="Cash" id ="234"></ChildAccount>
  </ParentAccount>
  <ParentAccount name ="Liabilities" id ="876">
    <ChildAccount name ="Account Payable" id ="983"></ChildAccount>
  </ParentAccount>
</Accounts>

now again, this is just in one cell and I need to bind it to TreeView to be like bellow

+ Asset

    - Cash

+ Liabilities

    - Account Payable

Hi,

jaffal

it only has one sell and its xml type.

According to your description ,for my experience you can get the xml string from your database and then create a XmlDocument object by using the XmlDocument.LoadXml("XMLstring") method which is used to load the XML document from the specified string.

jaffal

since I can't bind use sqldatasource as a datasource for the treeview and i cant use the XmlDataSource to read from the database

Using the XmlDocument object to bind data to the treeview control.

jaffal

now again, this is just in one cell and I need to bind it to TreeView to be like bellow

+ Asset

    - Cash

+ Liabilities

    - Account Payable

I would like to suggest you to check the sample below :

1.Code in page(.aspx):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TreeView ID="TreeView1" runat="server">
        </asp:TreeView>
    </div>
    </form>
</body>
</html>

If you use C# language:

2.Code in page(.cs):

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTree();
        }
    }
    public void BindTree()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(GetSource());
        XmlNode node = doc.DocumentElement;
        TreeNode treenode = null;
        foreach (XmlNode childnode in node.ChildNodes)
        {
            treenode = new TreeNode();
            XmlElement el = (XmlElement)childnode;
            treenode.Text = el.GetAttribute("name").ToString();
            AddChildNode(treenode,childnode);
            this.TreeView1.Nodes.Add(treenode);
        }
    }
    public void AddChildNode(TreeNode node,XmlNode xmlnode)
    {
        TreeNode childtreenode = null;
        foreach (XmlNode childnode in xmlnode.ChildNodes)
        {
            childtreenode = new TreeNode();
            XmlElement el = (XmlElement)childnode;
            childtreenode.Text = el.GetAttribute("name").ToString();
            AddChildNode(childtreenode,childnode);
            node.ChildNodes.Add(childtreenode);
        }
    }

    // You can get the string value from your database which as you mentioned in your post.
    public string GetSource()
    {
        string str = @"<Accounts> 
    <ParentAccount name=""Asset"" id=""123""> 
    <ChildAccount name =""Cash"" id =""234""></ChildAccount>            
    </ParentAccount> 
    <ParentAccount name =""Liabilities"" id =""876""> 
    <ChildAccount name =""Account Payable"" id =""983""></ChildAccount> 
    </ParentAccount> 
    </Accounts>";
        return str;
    }

Please do not forget the reference namespace:

using System.Xml;

If you use VB.NET language:

3.Code in page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindTree()
        End If
    End Sub
    Public Sub BindTree()
        Dim doc As New XmlDocument()
        doc.LoadXml(GetSource())
        Dim node As XmlNode = doc.DocumentElement
        Dim treenode As TreeNode = Nothing
        For Each childnode As XmlNode In node.ChildNodes
            treenode = New TreeNode()
            Dim el As XmlElement = DirectCast(childnode, XmlElement)
            treenode.Text = el.GetAttribute("name").ToString()
            AddChildNode(treenode, childnode)
            Me.TreeView1.Nodes.Add(treenode)
        Next
    End Sub
    Public Sub AddChildNode(ByVal node As TreeNode, ByVal xmlnode As XmlNode)
        Dim childtreenode As TreeNode = Nothing
        For Each childnode As XmlNode In xmlnode.ChildNodes
            childtreenode = New TreeNode()
            Dim el As XmlElement = DirectCast(childnode, XmlElement)
            childtreenode.Text = el.GetAttribute("name").ToString()
            AddChildNode(childtreenode, childnode)
            node.ChildNodes.Add(childtreenode)
        Next
    End Sub

    ' You can get the string value from your database which as you mentioned in your post.
    Public Function GetSource() As String
        Dim str As String = "<Accounts> " & vbCr & vbLf & "    <ParentAccount name=""Asset"" id=""123""> " & vbCr & vbLf & "    <ChildAccount name =""Cash"" id =""234""></ChildAccount>            " & vbCr & vbLf & "    </ParentAccount> " & vbCr & vbLf & "    <ParentAccount name =""Liabilities"" id =""876""> " & vbCr & vbLf & "    <ChildAccount name =""Account Payable"" id =""983""></ChildAccount> " & vbCr & vbLf & "    </ParentAccount> " & vbCr & vbLf & "    </Accounts>"
        Return str
    End Function

Hope it can help you.

Thanks To your reply, I couldnt find a solution, so i changed my structure and get rid of the xml Cell,i forgot to mark it as resolved though, but I think ur solution is very good.

[RESOLVED] ASP.NET Menu Custom Control Populated Using LINQ to SQL

 Hi all, I searched everywhere on the net for a guide of how to programmatically create an ASP.NET Menu Control populated using LINQ to SQL (with an unknown number of levels) and couldn't find one anywhere.  It took me a while to figure out the logistics of it so I thought I would post my final solution so that you don't have to spend time figuring this out for yourself.  Note that I am a self taught developer so I am potentially breaking any number standards coding protocols.  I welcome feedback, suggestions or questions on this code.

 

 

In this example I am working with an ASP.NET project named Virtual.   Non-Standard NameSpaces are Virtual.(tools, components) etc...

1. Create your database table that will eventually be used to populate your menu control.

USE [virtual]
GO


/****** Object:  Table [dbo].[menu]    Script Date: 06/16/2010 10:29:01 ******/
SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO


SET ANSI_PADDING ON
GO


CREATE TABLE [dbo].[menu](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[groupid] [int] NOT NULL,
	[parentid] [int] NOT NULL,
	[imageurl] [varchar](255) NULL,
	[popoutimageurl] [varchar](255) NULL,
	[navigateurl] [varchar](255) NULL,
	[text] [varchar](255) NULL,
	[target] [varchar](255) NULL,
	[value] [varchar](255) NULL,
	[tooltip] [varchar](255) NULL,
	[description] [varchar](255) NULL,
	[enabled] [int] NOT NULL,
	[selectable] [int] NOT NULL,
	[sort] [int] NOT NULL,
 CONSTRAINT [PK_menu] 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]


GO


SET ANSI_PADDING OFF
GO


ALTER TABLE [dbo].[menu] ADD  CONSTRAINT [DF_menu_groupid]  DEFAULT (1) FOR [groupid]
GO


ALTER TABLE [dbo].[menu] ADD  CONSTRAINT [DF_menu_parentid]  DEFAULT (0) FOR [parentid]
GO


ALTER TABLE [dbo].[menu] ADD  CONSTRAINT [DF_menu_enabled]  DEFAULT (1) FOR [enabled]
GO


ALTER TABLE [dbo].[menu] ADD  CONSTRAINT [DF_menu_selectable]  DEFAULT (1) FOR [selectable]
GO


ALTER TABLE [dbo].[menu] ADD  CONSTRAINT [DF_menu_sort]  DEFAULT (0) FOR [sort]
GO
using System;
using System.Configuration;
using System.Data;
using System.Data.Linq;
using System.Data.SqlClient;
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;



namespace Virtual
{
    public class MainMenu : WebControl
    {
        public MainMenu()
        {

           
        }


        protected override void CreateChildControls()
        {
            //Define working objects
            Menu _mnu = new Menu();
            
            Virtual.linq.linqDataContext _dc = new Virtual.linq.linqDataContext();
            XDocument _menuXML = new XDocument();
            XmlDataSource _xmlDS = new XmlDataSource();
           
            //Define LINQ to SQL Query
            XElement root = new XElement("Menus",
                            from m in _dc.menus
                            where m.parentid == 0
                            select GetMenuXML(m));

            _menuXML.Add(root);

            _xmlDS.Data = _menuXML.Document.ToString();
            _xmlDS.TransformFile = "/xslt/MainMenu.xslt";
            _xmlDS.XPath = "MenuItems/MenuItem";

            _mnu.DataSource = _xmlDS;


            BindMenu(_mnu);
            RenderMenu(_mnu);


            this.Controls.Add(_mnu);
            this.Controls.Add(_xmlDS);

            _mnu.DataBind();
           
        }


        private static XElement GetMenuXML(Virtual.linq.menu menu)
        {
            return new XElement("Menu",
                new XElement("MenuID", menu.id),
                new XElement("ParentID", menu.parentid),
                new XElement("ImageUrl", menu.imageurl),
                new XElement("PopOutImageUrl", menu.popoutimageurl),
                new XElement("NavigateUrl", menu.navigateurl),
                new XElement("Text", menu.text),
                new XElement("Target", menu.target),
                new XElement("Value", menu.value),
                new XElement("ToolTip", menu.tooltip),
                new XElement("Description", menu.description),
                new XElement("Target", menu.tooltip),
                new XElement("Enabled", menu.enabled),
                new XElement("Selectable", menu.selectable),
                menu.childMenus.Select(m => GetMenuXML(m)));
        }

        private static void BindMenu(Menu _mnu)
        {
            MenuItemBinding _mnuBinding = new MenuItemBinding();

            //_mnuBinding.ImageUrlField = "ImageUrl";
            //_mnuBinding.PopOutImageUrlField = "PopOutImageUrl";
            //_mnuBinding.SelectableField = "Selectable";
            //_mnuBinding.TargetField = "Target";
            _mnuBinding.TextField = "Text";
            //_mnuBinding.ToolTipField = "ToolTip";
            //_mnuBinding.ValueField = "Value";

            _mnu.DataBindings.Add(_mnuBinding);

            
        }


        private static void RenderMenu(Menu _mnu)
        {
            //Set Behaviour of Control
            _mnu.Orientation = Orientation.Horizontal;
            _mnu.StaticDisplayLevels = 1;
            _mnu.MaximumDynamicDisplayLevels = 2;
            _mnu.Enabled = true;

            //Set CSS Classes To Control Look and Feel
            _mnu.CssClass = "Menu";
            _mnu.StaticMenuStyle.CssClass = "Menu";
            _mnu.StaticMenuItemStyle.CssClass = "MenuItem";
            _mnu.StaticHoverStyle.CssClass = "MenuItemHover";
            _mnu.StaticSelectedStyle.CssClass = "MenuSelectedStyle";
            _mnu.DynamicMenuStyle.CssClass = "SubMenu";
            _mnu.DynamicMenuItemStyle.CssClass = "SubMenuItem";
            _mnu.DynamicHoverStyle.CssClass = "SubMenuHover";
            _mnu.DynamicSelectedStyle.CssClass = "SubMenuSelectedStyle";
        }

       
    }
}

Thank you for your sharing.  Cool

hello >>

Thanks alot for sharing this code.

I run your class successfully .............
but what is the next step , i mean how can i render the menu on the web page.

Thanks in advance

[RESOLVED] How to create dynamic n number of link buttons

I want to create n numbers of dynamic link buttons runtime.
I will have an xml file which has the format like
<category>
<link>
Link1
</link>
<pdf>
PDF1
</pdf>
</category>
<category>
<link>
Link2
</link>
<pdf>
PDF2
</pdf>
</category>
<category>
<link>
Link3
</link>
<pdf>
PDF3
</pdf>
</category>
........
........
........
and so on

I have to take the element within the <Link> tag and make it as a linkbutton
 and when user will click the button, it will open a pdf file named within the <pdf> tag.
It may happen that the xml has 10 such tags, it may have 200 tags, based on the number of such tags,
our link buttons will be created and pdf files will be opened on clicking the respective linkbuttons. How can I achieve this?

Use a data binding control(DataGrid/GridView/Repeater) along with an XMLDataSource control. Try the below snippet (assuming your xml file name is Categories.xml)

Create an XML Data Source control

<asp:XmlDataSource ID="dsCategories" runat="server" DataFile="Categories.xml" XPath="Categories/category"></asp:XmlDataSource>

Create a DataGrid

<asp:DataGrid ID="dgCategories" runat="server" DataSourceID="dsCategories" 
            AutoGenerateColumns="false" onitemcommand="dgCategories_ItemCommand"<
            <Columns<
                <asp:TemplateColumn HeaderText="Download"<
                    <ItemTemplate<
                        <asp:LinkButton ID="link" runat="server" Text='<%#XPath("link")%<' CommandName="Download" CommandArgument='<%#XPath("pdf")%>'<</asp:LinkButton<
                    </ItemTemplate<
                </asp:TemplateColumn<
            </Columns<
        </asp:DataGrid<

Code behind

protected void dgCategories_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            string pdfFileName = e.CommandArgument.ToString();
            ///.... Code to download
        }
    }

SreejithGopinathan

Create a DataGrid

<asp:DataGrid ID="dgCategories" runat="server" DataSourceID="dsCategories"
            AutoGenerateColumns="false" onitemcommand="dgCategories_ItemCommand"<
            <Columns<
                <asp:TemplateColumn HeaderText="Download"<
                    <ItemTemplate<
                        <asp:LinkButton ID="link" runat="server" Text='<%#XPath("link")%<' CommandName="Download" CommandArgument='<%#XPath("pdf")%>'<</asp:LinkButton<
                    </ItemTemplate<
                </asp:TemplateColumn<
            </Columns<
        </asp:DataGrid<

It looks like this code got messed up, it should be this:

<asp:DataGrid ID="dgCategories" runat="server" DataSourceID="dsCategories" 
            AutoGenerateColumns="false" onitemcommand="dgCategories_ItemCommand">
            <Columns>
                <asp:TemplateColumn HeaderText="Download">
                    <ItemTemplate>
                        <asp:LinkButton ID="link" runat="server" Text='<%#XPath("link")%>' CommandName="Download" CommandArgument='<%#XPath("pdf")%>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateColumn>
            </Columns>
        </asp:DataGrid>