Tuesday, 16 April 2013

Menu handle by Treeview

<asp:TreeView ID="treeviwExample"  runat="server" ImageSet="Arrows">
            <HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
            <NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />
            <ParentNodeStyle Font-Bold="False" />
            <SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px" VerticalPadding="0px" />           
        </asp:TreeView>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class Treeview_checkchanges : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTreeViewControl();
        }
    }
    private void BindTreeViewControl()
    {
        try
        {
            DataSet ds = GetDataSet("Select MenuId,MenuName,ParentId from tblMenuSite where deleted=0 order by groupid desc");
            DataRow[] Rows = ds.Tables[0].Select("ParentId IS NULL"); // Get all parents nodes
            for (int i = 0; i < Rows.Length; i++)
            {
                TreeNode root = new TreeNode(Rows[i]["MenuName"].ToString(), Rows[i]["MenuId"].ToString());
                root.SelectAction = TreeNodeSelectAction.Expand;
                CreateNode(root, ds.Tables[0]);
                treeviwExample.Nodes.Add(root);
            }
        }
        catch (Exception Ex) { throw Ex; }
    }

    public void CreateNode(TreeNode node, DataTable Dt)
    {
        DataRow[] Rows = Dt.Select("ParentId =" + node.Value);
        if (Rows.Length == 0) { return; }
        for (int i = 0; i < Rows.Length; i++)
        {
            TreeNode Childnode = new TreeNode(Rows[i]["MenuName"].ToString(), Rows[i]["MenuId"].ToString());
            Childnode.SelectAction = TreeNodeSelectAction.Expand;
            node.ChildNodes.Add(Childnode);
            CreateNode(Childnode, Dt);
        }
    }
    private DataSet GetDataSet(string Query)
    {
        DataSet Ds = new DataSet();
        try
        {
            string strCon = @"Data Source=;Initial Catalog=;uid=sa;pwd=;";
            SqlConnection Con = new SqlConnection(strCon);
            SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
            Da.Fill(Ds);
        }
        catch (Exception) { }
        return Ds;
    }
}

No comments:

Post a Comment