본문 바로가기

Programming/ASP .NET

TreeView에서 체크박스 이벤트 발생시키기

목표 : TreeView의 각 노드에 체크박스를 두고 부모를 체크 하면 자식들은 모두 부모에 따름

웹 검색을 하다가 유용한 자료가 있어서 퍼왔습니다. 출처는 제일 아래에 있네요.
저는 이 소스를 다 쓴건 아니고 스크립트 부분만 썼습니다. PostBack 방식으로 했는데.
아무래도 좀 불편한거 같네요...
=====================================================================
체크 박스 이므로 여러개를 선택할수 있도록 체크 박스를 선택할때마다 이벤트가 발생하지는 않습니다.

그래서 약간의 편법을 이용한 자료를 올려 보겠습니다.


1. postback 처리

<%@ Page Language="C#" %>

<script runat="server">
protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
    foo(e.Node, e.Node.Checked);
}
private void foo(TreeNode e, bool check)
{
    e.Checked = check;
    foreach (TreeNode t in e.ChildNodes)
    {
        foo(t, check);
    }
}

</script>


<script>
function foo()
{
    var o = window.event.srcElement;
    if (o.tagName == "INPUT" && o.type == "checkbox"){
        __doPostBack("","");
    }
}
</script>

<html>

<head id="Head1" runat="server">

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <asp:TreeView onclick="foo()" ID="TreeView1" runat="server" ExpandDepth="4" EnableClientScript="False"

                ShowCheckBoxes="All" OnTreeNodeCheckChanged="TreeView1_TreeNodeCheckChanged">

                <Nodes>

                    <asp:TreeNode ShowCheckBox="True" Value="a" Text="a">

                        <asp:TreeNode Value="aa" Text="aa">

                            <asp:TreeNode Text="aaa" Value="aaa">

                                <asp:TreeNode Text="aaaa" Value="aaaa"></asp:TreeNode>

                                <asp:TreeNode Text="abbb" Value="abbb"></asp:TreeNode>

                            </asp:TreeNode>

                            <asp:TreeNode Text="bbb" Value="bbb">

                                <asp:TreeNode Text="bbbb" Value="bbbb"></asp:TreeNode>

                            </asp:TreeNode>

                            <asp:TreeNode Text="ccc" Value="ccc"></asp:TreeNode>

                        </asp:TreeNode>

                    </asp:TreeNode>

                    <asp:TreeNode Text="bb" Value="bb">

                        <asp:TreeNode Text="bbb" Value="bbb"></asp:TreeNode>

                    </asp:TreeNode>

                </Nodes>

            </asp:TreeView>

        </div>

    </form>

</body>

</html>


2. 웹페이지상에서 스크립트로 처리 ..

<%@ Page Language="C#" %>

<html >

<head id="Head1" runat="server">

    <title>XML Tree View</title>

    <script language="javascript">

        //***each node in a TreeNode is a <table> and the level that a node exists on is

        //***decided by the number of columns in the table (that are use to push it out)

        //***CAVEATS

        //***(1)This only works with a static TreeView

        //***(2)This only works properly if EnableClientScript=true

        //***(3)If Microsoft(R) changes the HTML use to render the Nodes then this is obsolete

        //***(4)This does not account for all design considerations, but should be a good start

        function client_OnTreeNodeChecked() {      

            var obj = window.event.srcElement;

            var treeNodeFound = false;

            var checkedState;

           

            if (obj.tagName == "INPUT" && obj.type == "checkbox") {

                //easier to read

                var treeNode = obj;

               

                //record the checked state of the TreeNode

                checkedState = treeNode.checked;

               

                //work our way back to the parent <table> element      

                do {

                    obj = obj.parentElement;

                } while (obj.tagName != "TABLE")

           

                //keep track of the padding level for comparison with any children

                var parentTreeLevel = obj.rows[0].cells.length;

           

                //get all the TreeNodes inside the TreeView (the parent <div>)

                var tables = obj.parentElement.getElementsByTagName("TABLE");

               

                //total number of TreeNodes

                var numTables = tables.length


                if (numTables > 1) {

                    //cycle through all the TreeNodes

                    //until we find the TreeNode we checked

                    for (i=0; i < numTables; i++) {

                        if (tables[i] == obj) {

                            treeNodeFound = true;

                            i++;

                            if (i == numTables) {

                                //if we're on the last

                                //TreeNode then stop

                                return;

                            }

                        }

                       

                        //when found examine the TreeLevel of each of

                        //the preceding TreeNodes

                        if (treeNodeFound == true) {

                            var childTreeLevel = tables[i].rows[0].cells.length;

                           

                            //if the current node is under the parent

                            //the level will be deeper (greater)

                            if (childTreeLevel > parentTreeLevel) {

                           

                                //jump to the last cell... it contains the checkbox

                                var cell = tables[i].rows[0].cells[childTreeLevel - 1];

                               

                                //set the checkbox to match the checkedState

                                //of the TreeNode that was clicked

                                var inputs = cell.getElementsByTagName("INPUT");

                                inputs[0].checked = checkedState;

                            } else {

                                //if any of the preceding TreeNodes are not deeper stop

                                return;

                            }//end if

                        }//end if

                    }//end for

                }//end if

            }//end if

        }//end function

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <asp:XmlDataSource ID="xmlSrc" runat="server" />

    <div>

    <asp:TreeView

        onclick="client_OnTreeNodeChecked();"

        ID="staticTree"

        runat="server"

        ExpandDepth="0"

        ShowCheckBoxes="All"

        EnableClientScript="true"

        ShowExpandCollapse="true"

        ShowLines="true"

        >

        <Nodes>

            <asp:TreeNode Text="Table of Contents"

            SelectAction="None">

                   

                <asp:TreeNode Text="Chapter One">

               

                    <asp:TreeNode Text="Section 1.0">

                   

                        <asp:TreeNode Text="Topic 1.0.1"/>

                        <asp:TreeNode Text="Topic 1.0.2"/>

                        <asp:TreeNode Text="Topic 1.0.3"/>

                   

                    </asp:TreeNode>

                   

                    <asp:TreeNode Text="Section 1.1">

                   

                        <asp:TreeNode Text="Topic 1.1.1"/>

                        <asp:TreeNode Text="Topic 1.1.2"/>

                        <asp:TreeNode Text="Topic 1.1.3"/>

                        <asp:TreeNode Text="Topic 1.1.4"/>

                   

                    </asp:TreeNode>

               

                </asp:TreeNode>

               

                <asp:TreeNode Text="Chapter Two">

               

                    <asp:TreeNode Text="Section 2.0">

                   

                        <asp:TreeNode Text="Topic 2.0.1"/>

                        <asp:TreeNode Text="Topic 2.0.2"/>

                   

                    </asp:TreeNode>

               

                </asp:TreeNode>

               

            </asp:TreeNode>

            <asp:TreeNode Text="Appendix A" />

            <asp:TreeNode Text="Appendix B" />

            <asp:TreeNode Text="Appendix C" />

        </Nodes>

    </asp:TreeView>

    </div>

    </form>

</body>

</html>


필요한걸 사용하시면 될듯하네요 ..


=========================

Visual C# MVP Freecoder

http://freecoder.pe.kr

=========================