玄铁剑

成功的途径:抄,创造,研究,发明...
posts - 128, comments - 42, trackbacks - 0, articles - 174

TreeGrid實現方法

Posted on 2008-02-20 17:16 玄铁剑 阅读(2871) 评论(1)  编辑 收藏 引用 所属分类: Javascript
方法1:

Sample Image - treelistcontrol.v3.gif

Introduction

This is my third attempt at making a TreeListControl for Internet Explorer-based web applications. The first was very slow and required ASP to generate a tree. The second has lots of features, and even resizable columns, but, while it did not suffer from the freeze-up delays that occurred in the first one, was generally sluggish in operation if there were more than a few nodes on the screen. This latest version has tighter code and is generally more versatile all round. It doesn't have resizable columns, but it shouldn't be too hard to put them in. If I do that, I'll upload the updated version here. The only other major limitation of this control is that it is fixed-width. That is, you have to specify the exact width of each column, and this determines the control width.

Features that version 3.0 has are:

  • Enable/disable column headings
  • Enable/disable root node
  • The ability to choose which column the tree appears in
  • Dynamic loading of branches via XML files
  • Completely dynamic updating of the tree structure after it has been generated, including:
    • remove nodes
    • add new nodes
    • remove nodes and re-add them somewhere else
    • insert before or after a specified node
    • expand/collapse branches
  • optional row onclick action
  • row highlights while being pointed at
  • prevent specified columns from firing the row onclick event (e.g. for a column of checkboxes)

To use the control, simply include treelistcontrol.js and treelistcontrol.css in your html file, then, inside the element (body tag, div tag, or where ever) you want to render the tree inside, place a script tag and build the tree according to the API. A demo of how to do this is inside the included zip file.

Usage

See the API below for explanations of the tree's objects, and the file demo.htm for an example of how to use the tree.

  1. Create a tree control
  2. Create and add the columns to the tree
  3. Add all the initial nodes to the tree
  4. document.write the tree object to the page

Tree List Control v3.0 API

TreeListControl

TreeListControl(strRootNodeLabel, strRootNodeIconSrc, boolHideColumnHeadings, boolHideRootNode)

  • strRootNodeLabel: the label to use for the root node
  • strRootNodeIconSrc: the path to the node's icon
  • boolHideColumnHeadings: don't show the column headings
  • boolHideRootNode: don't show the root node

Properties

  • showColumnHeadings: hide/show the column headings. The visibility of the column headings will automatically change depending on the state of this property.
  • showRootNode: hide/show the root node. The visibility of the root node will automatically change depending on the state of this property.
  • all: this is a collection (array) contain references to all the nodes that were assigned a non-null refKey when added to the tree. usage: mytree.all['mynoderefKey']
  • allNodes: this is a collection containing references to every node in the tree, indexed by the node's automatically assigned ID property.
  • rootNode: a reference to the tree's root node. This is of type TreeListControlNode.
  • iconPath: the path to the location where the tree's images are stored. The default is 'tlcimages/'.

Methods

  • addColumn( oColumnObject ): adds a column to the tree. Do not use this once the tree has been rendered to the page. Pass in a reference to a TreeListControlColumn object that defines the column's parameters.
  • add( oNodeObject ): appends a node to the children of the root node. Pass in a reference to a previously created node.

TreeListControlColumn

TreeListControlColumn (intWidth, strTitle, boolPreventRowClickEvents)

  • intWidth: the width, in pixels, of the column.
  • strTitle: the heading/title of the column. Use a zero-length string if no title is desired.
  • boolPreventRowClickEvents: when a row is clicked, it fires the onclick event for that row. Setting this parameter to true will prevent clicks in this row from firing that event.

TreeListControlNode

TreeListControlNode (boolShowChildren, strIconSrc, strXMLSrc, strReferenceKey)

  • boolShowChildren: this specifies the initial expand/collapse state for the node.
  • strIconSrc: the path to the icon image to use.
  • strXMLSrc: if the children of this node are to be loaded at run-time when the node is expanded, this parameter should contain the URL of the XML file. Set to null or '' if not used.
  • strReferenceKey: if you want to use your own identifiers for each node, instead of the automatically-assigned ID that each node has, specify the identifier here. It can be an integer or a string, and, once the node has been added to the tree, you can access the node via the all property of the TreeListControl object.

Properties

  • onclick: the javascript to execute when the onclick event fires for that node. Only set this before the node has been added to the tree.

Methods

  • expand: shows the node's children.
  • collapse: hides the node's children.
  • setText( strColumn1, strColumn2, ..., strColumnN ): sets the node's text in each column.
  • setColumnText( intColumn, strText ): sets the text for the node in the specified column.
  • add( oNodeObject ): appends a node object to this node's children. DO NOT use this method if this node has not yet been added to the tree.
  • insertBefore( oNodeObject ): inserts the supplied node immediately before this node.
  • insertAfter( oNodeObject ): inserts the supplied node directly after this node.
  • remove(): removes this node from the tree completely and returns a reference to the node so that it can be reinserted elsewhere if desired.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


方法2:

Sample Image - wsGridCtrl.gif

Introduction

This article demonstrates a Tree Grid control for JScript.

How to use

// Create wsGrid Instance
 m_wsGridCtrl = new wsGridCtrl();
// Initialize
 // Param1: width
 // Param2: OnMouseOver Color
 m_wsGridCtrl.initializeDocument(500, "#FF9999");
// Titles Create
 // Param1: Text
 // Param2: Width
 m_wsGridCtrl.InsTab("Title", "*");
m_wsGridCtrl.InsTab("Content", "400");
// Insert Item Example
 // Param1: Parent Item
 // Param2: Item. If title is two..
//          you must write two Items. (delimiter is ';')
 // Param3: hyper link (it also delimiter is ';')
 m_wsGridCtrl.InsItem(null, "Menu1;Content1;",
"http://yahoo.com;http://google.com;", "_self;_blank;");
m_wsGridCtrl.InsItem(null, "Menu2;Content2;",
"http://yahoo.com;http://google.com;", "_blank;_blank;");
// Sub Item Example
 var iItem = m_wsGridCtrl.InsItem(null, "Menu3;Content3;",
"http://yahoo.com;http://google.com;", "_blank;_blank;");
m_wsGridCtrl.InsItem(iItem, "Menu5;Content5;",
"http://yahoo.com;http://google.com;", "_blank;_blank;");
m_wsGridCtrl.InsItem(null, "Menu6;Content6;",
"http://yahoo.com;http://google.com;", "_blank;_blank;");
m_wsGridCtrl.InsItem(null, "Menu7;Content7;",
"http://yahoo.com;http://google.com;", "_blank;_blank;");
// finilly generate code (It is important!)
 m_wsGridCtrl.GenerateCode();
// First state setting (ExpandAllTree or RecudeAllTree)
 m_wsGridCtrl.RecudeAllTree();
// m_wsGridCtrl.ExpandAllTree();

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

方法3,方法比較笨拙,但也能夠實現大多數的TreeGrid,部分代碼思路如下:
    string FstColor = "#ECF0F7";
    string SecColor = "#FFFFFF";

 //tbModuleList is Table
    protected void DrawTreeGrid()
    {
        tbModuleList.Rows.Clear();
        TreeView MyTreeView = new TreeView();
        BuildTree(MyTreeView);
        BuildGridData(MyTreeView);
    }
 
    protected void BuildTree(TreeView MainTree)
    {
        MainTree.Nodes.Clear();
        TreeNode newItem;
  //.....
        //BuildSubTree(ref newItem, ...);
        MainTree.Nodes.Add(newItem);
    }

    protected void BuildSubTree(ref TreeNode pNode, string ItemID)
    {
        TreeNode newItem;
        newItem = new TreeNode();
        //BuildSubTree(ref newItem, ...);
        pNode.ChildNodes.Add(newItem);
    }

    protected void addLabelCol(TableRow tRow, int irow, int icol, string strText, int iwidth, HorizontalAlign position)
    {
        TableCell tCell;
        Label label;
        tCell = new TableCell();
        tCell.VerticalAlign = VerticalAlign.Middle;
        tCell.HorizontalAlign = position;
        tRow.Cells.Add(tCell);
        label = new Label();
        label.ID = "label_" + irow.ToString() + icol.ToString();
        label.Text = strText;
        label.Font.Bold = true;
        label.Width = Unit.Pixel(iwidth);
        label.EnableTheming = true;
        tCell.Controls.Add(label);
    }

    protected void addBranchImgButtonCol(TableCell tCell, int irow, int icol, string strText)
    {
        ImageButton imgBranchBtn;
        imgBranchBtn = new ImageButton();
        imgBranchBtn.CommandArgument = irow.ToString();
        imgBranchBtn.ID = "imgBranchBtn_" + irow.ToString() + icol.ToString();
        imgBranchBtn.ImageUrl = "~/App_Themes/Default/images/collapse.jpg";
        imgBranchBtn.Click += new ImageClickEventHandler(imgBranchBtn_Click);
        tCell.Controls.Add(imgBranchBtn);
    }

    protected int nbspCount(string str)
    {
        int icount = 0;
        object[] objlist = UDF.ConvertToArray(str, ';');
        foreach (object obj in objlist)
        {
            if (obj.ToString() == "&nbsp")
            {
                icount++;
            }
        }
        return icount;
    }

    protected void imgBranchBtn_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton imgBranchBtn = (ImageButton)sender;
        int irow = UDF.ToInt(imgBranchBtn.CommandArgument,0)-1;
        int iCurCount = 0;
        string str="";
        if (imgBranchBtn.ImageUrl.Contains("collapse.jpg") == true)
        {
            imgBranchBtn.ImageUrl = "~/App_Themes/Default/images/expand.jpg";
            if (irow != -1)
            {
                if (tbModuleList.Rows[irow].Cells[1].Controls[0] is LinkButton)
                {
                    str = ((LinkButton)tbModuleList.Rows[irow].Cells[1].Controls[0]).Text;
                }
                if (tbModuleList.Rows[irow].Cells[1].Controls[0] is ImageButton)
                {
                    str = ((LinkButton)tbModuleList.Rows[irow].Cells[1].Controls[1]).Text;
                }
                iCurCount = nbspCount(str);
                for (int i = irow + 1; i < tbModuleList.Rows.Count; i++)
                {
                    if (tbModuleList.Rows[i].Cells[1].Controls[0] is LinkButton)
                    {
                        str = ((LinkButton)tbModuleList.Rows[i].Cells[1].Controls[0]).Text;
                    }
                    if (tbModuleList.Rows[i].Cells[1].Controls[0] is ImageButton)
                    {
                        str = ((LinkButton)tbModuleList.Rows[i].Cells[1].Controls[1]).Text;
                    }

                    if (nbspCount(str) > iCurCount)
                    {
                        tbModuleList.Rows[i].Visible = false;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        else
        {
            imgBranchBtn.ImageUrl = "~/App_Themes/Default/images/collapse.jpg";
            if (irow != -1)
            {
                if (tbModuleList.Rows[irow].Cells[1].Controls[0] is LinkButton)
                {
                    str = ((LinkButton)tbModuleList.Rows[irow].Cells[1].Controls[0]).Text;
                }
                if (tbModuleList.Rows[irow].Cells[1].Controls[0] is ImageButton)
                {
                    str = ((LinkButton)tbModuleList.Rows[irow].Cells[1].Controls[1]).Text;
                }
                iCurCount = nbspCount(str);
                for (int i = irow + 1; i < tbModuleList.Rows.Count; i++)
                {
                    if (tbModuleList.Rows[i].Cells[1].Controls[0] is LinkButton)
                    {
                        str = ((LinkButton)tbModuleList.Rows[i].Cells[1].Controls[0]).Text;
                    }
                    if (tbModuleList.Rows[i].Cells[1].Controls[0] is ImageButton)
                    {
                        str = ((LinkButton)tbModuleList.Rows[i].Cells[1].Controls[1]).Text;
                    }

                    if (nbspCount(str) > iCurCount)
                    {
                        tbModuleList.Rows[i].Visible = true;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
    }

    protected void addImgButtonCol(TableRow tRow, int irow, int icol, string strText)
    {
        TableCell tCell;
        ImageButton imgBtn;
        tCell = new TableCell();
        tCell.VerticalAlign = VerticalAlign.Middle;
        tCell.HorizontalAlign = HorizontalAlign.Left;
        tRow.Cells.Add(tCell);
        imgBtn = new ImageButton();
        imgBtn.CommandArgument = strText;
        imgBtn.ID = "imgBtn_" + irow.ToString() + icol.ToString();
        imgBtn.ImageUrl = "~/App_Themes/Default/images/delete.gif";
        imgBtn.Click += new ImageClickEventHandler(imgBtn_Click);
        AjaxControlToolkit.ConfirmButtonExtender confirm = new AjaxControlToolkit.ConfirmButtonExtender();
        confirm.TargetControlID = imgBtn.ID;
        confirm.ConfirmText = ToolBar.GetDeleteMsg();
        confirm.Enabled = true;

        tCell.Controls.Add(imgBtn);
        tCell.Controls.Add(confirm);
    }

    protected void imgBtn_Click(object sender, ImageClickEventArgs e)
    {
        string strID = ((ImageButton)sender).CommandArgument;
    }

    protected void addLnkButtonCol(TableRow tRow, int irow, int icol, string strText, int iwidth,Boolean addBranchICON)
    {
        TableCell tCell;
        LinkButton lnkBtn;
        tCell = new TableCell();
        tCell.VerticalAlign = VerticalAlign.Middle;
        tCell.HorizontalAlign = HorizontalAlign.Left;
        tRow.Cells.Add(tCell);
        lnkBtn = new LinkButton();
        lnkBtn.ID = "lnkBtn_" + irow.ToString() + icol.ToString();
        lnkBtn.Text = strText;
        lnkBtn.Click += new EventHandler(lnkBtn_Click);
        lnkBtn.Font.Bold = true;
        lnkBtn.Width = Unit.Pixel(iwidth);
        lnkBtn.EnableTheming = true;

        if (addBranchICON == true)
        {
            addBranchImgButtonCol(tCell, irow, icol, strText);
        }

        tCell.Controls.Add(lnkBtn);
    }

    //select this record
    protected void lnkBtn_Click(object sender, EventArgs e)
    {
        string str = ((LinkButton)sender).Text;
    }

    protected void BuildSubGridData(TreeNode pNode, ref int iRol)
    {
        TableRow tRow;
        Module mdl = null;
        for (int i = 0; i < pNode.ChildNodes.Count; i++)
        {
            int iCol = 1;
            if (pNode.ChildNodes[i].ChildNodes.Count > 0)
            {
                tRow = new TableRow();
                if (iRol % 2 == 0)
                {
                    tRow.BackColor = Color.FromName(FstColor);
                }
                else
                {
                    tRow.BackColor = Color.FromName(SecColor);
                }
                tbModuleList.Rows.Add(tRow);
                ++iRol;
                addLabelCol(tRow, iRol, iCol++, "ColumA.Value", 100, HorizontalAlign.Left);
                addLabelCol(tRow, iRol, iCol++, "ColumB.Value", 100, HorizontalAlign.Left);
                addLabelCol(tRow, iRol, iCol++, "ColumC.Value", 100, HorizontalAlign.Left);
                BuildSubGridData(pNode.ChildNodes[i], ref iRol);
                continue;
            }
            iCol = 1;
            tRow = new TableRow();
            if (iRol % 2 == 0)
            {
                tRow.BackColor = Color.FromName(FstColor);
            }
            else
            {
                tRow.BackColor = Color.FromName(SecColor);
            }
   tbModuleList.Rows.Add(tRow);
            ++iRol;
   addLabelCol(tRow, iRol, iCol++, "ColumA.Value", 100, HorizontalAlign.Left);
   addLabelCol(tRow, iRol, iCol++, "ColumB.Value", 100, HorizontalAlign.Left);
   addLabelCol(tRow, iRol, iCol++, "ColumC.Value", 100, HorizontalAlign.Left);
        }
    }

    protected void BuildGridData(TreeView MainTree)
    {
        int iRol = 0;
        int iCol = 1;
        TableRow tRow;
        Module mdl = null;
        tRow = new TableRow();
        tRow.BackColor = Color.FromName("#84AED8");
        tbModuleList.Rows.Add(tRow);
        iRol++;
        addLabelCol(tRow, iRol, iCol++, "TitleA", 100, HorizontalAlign.Center);
        addLabelCol(tRow, iRol, iCol++, "TitleB", 100, HorizontalAlign.Center);
        addLabelCol(tRow, iRol, iCol++, "TitleC", 100, HorizontalAlign.Center);

        for (int i = 0; i < MainTree.Nodes.Count; i++)
        {
            iCol = 1;
            tRow = new TableRow();
            if (iRol % 2 == 0)
            {
                tRow.BackColor = Color.FromName(FstColor);
            }
            else
            {
                tRow.BackColor = Color.FromName(SecColor);
            }
            UDF.SetRowHighlight(tRow);
            tbModuleList.Rows.Add(tRow);
            iRol++;
   addLabelCol(tRow, iRol, iCol++, "ColumA.Value", 100, HorizontalAlign.Left);
   addLabelCol(tRow, iRol, iCol++, "ColumB.Value", 100, HorizontalAlign.Left);
   addLabelCol(tRow, iRol, iCol++, "ColumC.Value", 100, HorizontalAlign.Left);
            if (MainTree.Nodes[i].ChildNodes.Count > 0)
            {
                BuildSubGridData(MainTree.Nodes[i], ref iRol);
            }
        }

        DefaultCollapse();
    }

    protected void DefaultCollapse()
    {
        string str;
        int iCurCount = 0;
        ImageButton imgBranchBtn;
        for (int k = 0; k < tbModuleList.Rows.Count; k++)
        {
            if (tbModuleList.Rows[k].Cells[1].Controls[0] is ImageButton)
            {
                imgBranchBtn = (ImageButton)tbModuleList.Rows[k].Cells[1].Controls[0];
                if (imgBranchBtn.ImageUrl.Contains("collapse.jpg") == true)
                {
                    imgBranchBtn.ImageUrl = "~/App_Themes/Default/images/expand.jpg";
                    str = ((LinkButton)tbModuleList.Rows[k].Cells[1].Controls[1]).Text;
                    iCurCount = nbspCount(str);
                    for (int i = k + 1; i < tbModuleList.Rows.Count; i++)
                    {
                        if (tbModuleList.Rows[i].Cells[1].Controls[0] is LinkButton)
                        {
                            str = ((LinkButton)tbModuleList.Rows[i].Cells[1].Controls[0]).Text;
                        }
                        if (tbModuleList.Rows[i].Cells[1].Controls[0] is ImageButton)
                        {
                            str = ((LinkButton)tbModuleList.Rows[i].Cells[1].Controls[1]).Text;
                        }

                        if (nbspCount(str) > iCurCount)
                        {
                            if (tbModuleList.Rows[i].Cells[1].Controls[0] is ImageButton)
                            {
                                continue;
                            }
                            else
                            {
                                tbModuleList.Rows[i].Visible = false;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
    }

Feedback

# re: TreeGrid實現方法  回复  更多评论   

2009-06-09 14:36 by 月漩涡
汗。英文不太好。还没注释。郁闷。。。
只有注册用户登录后才能发表评论。