ASP.NET PostBack on selecting checkbox of treeview

扶醉桌前 提交于 2019-11-30 23:58:18

There is no AutoPostBack property on TreeView. And as per the MSDN, The TreeNodeCheckChanged event is raised when a check box in the TreeView control changes state between posts to the server

You need to do something else, like mentioned on this link

1) Add on click attribute to TreeView1 on page load

protected void Page_Load(object sender, EventArgs e)
{
     TreeView1.Attributes.Add("onclick", "postBackByObject()");
}

2) add java script function and do the post back

    <script type="text/javascript">

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

3). Implement TreeNodeCheckChanged event

protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {
            // do stuff
        } 

When you're dynamically binding the TreeView the TreeNodeCheckChanged event will not be fired when you click the checkbox, you can overcome this quite easily though with a little bit of javascript:

ASPX:

<head runat="server">
    <script type="text/javascript">
        function fireCheckChanged() {
            var o = window.event.srcElement;
            if (o.tagName == "INPUT" && o.type == "checkbox") {
                __doPostBack("", "");
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TreeView ID="treevCourses" runat="server" 
            ShowCheckBoxes="Parent,Leaf" Width="100%" Height="16px" ImageSet="Contacts" 
            ontreenodecheckchanged="check_changed" />
    </div>
    </form>
</body> 

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var data = new XmlDataSource();
        data.DataFile = Server.MapPath("~/input.xml");
        treevCourses.DataSource = data;
        treevCourses.DataBind();

        treevCourses.Attributes.Add("onclick", "fireCheckChanged()");
    }
}

protected void check_changed(object sender, TreeNodeEventArgs e)
{
    string clickedNode = e.Node.Text;
    System.Diagnostics.Debugger.Break();
}

Is this a good idea - Obviously sending requests to the server everytime the checkbox state is changed can become resource intensive but if you cannot replicate the same functionality using javascript then this is your only option

Replace this line

treevCourses.Attributes.Add("onclick", "fireCheckChanged()");

with

treevCourses.Attributes.Add("onclick", "fireCheckChanged(event)");

and replace the script with

  function fireCheckChanged(e) {
 var evnt = ((window.event) ? (event) : (e));
 var element = evnt.srcElement || evnt.target;

 if (element.tagName == "INPUT" && element.type == "checkbox") {
      __doPostBack("", "");
}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!