views:

742

answers:

1

The treeview has leaf node checkboxes.I need to validate the treeview if atleast one of the node is checked and not more than a specfic(say 3 nodes) number of nodes a user can select. Note:The Treeview is a asp.net treeview(not an ajax treeview)

+4  A: 

Alright, since you didn't mentioned what type of validation you want, I'll do both client side and server side. My TreeView is named tvTest
First, add a CustomValidator to you Asp.Net page:

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ClientValidate"
  ErrorMessage="CustomValidator" Display="Dynamic" OnServerValidate="CustomValidator1_ServerValidate">*</asp:CustomValidator>

Note: don't set the ControlToValidate property.
Next, add this script (also to your Asp.Net page) for client side validation:

<script type="text/javascript">

  function ClientValidate(source, arguments) {
    var treeView = document.getElementById("<%= tvTest.ClientID %>");
    var checkBoxes = treeView.getElementsByTagName("input");
    var checkedCount = 0;
    for (var i = 0; i < checkBoxes.length; i++) {
      if (checkBoxes[i].checked) {
        checkedCount++;
      }
    }
    if (checkedCount > 0 && checkedCount < 4) {
      arguments.IsValid = true;
    } else {
      arguments.IsValid = false;
    }
  }        

</script>

And last, add this to your code-behind for server side validation:

protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args) {
  if (tvTest.CheckedNodes.Count > 0 && tvTest.CheckedNodes.Count < 4) {
    args.IsValid = true;
  } else {
    args.IsValid = false;
  }
}

Of course, you'll want to change the limits for the minimum and maximum number of nodes the user can check.

Julien Poulin
+1 - nice solution.
adrianos