How to uncheck all checkbox in treeview nodes? - asp.net

i am working on an application in asp.net.I have used a treeview to show Category.After storing the checked node value into database i want to uncheck all the treeview nodes. for this i have the following code:
foreach (TreeNode node in TreeView1.CheckedNodes)
{
node.Checked=false;
}
but it is showing error:
Collection was modified; enumeration operation may not execute
please help me.
thanks!

foreach is read only and you can't change collection into foreach.
you must use for loop:
for (int i = 0; i < TreeView1.Nodes.Count; i++)
{
TreeView1.Nodes[i].Checked = false;
}

//foreach (TreeNode node in TreeView1.CheckedNodes)
for(int i=0; i<TreeView1.CheckedNodes.Count; i++)
{
TreeNode node = TreeView1.CheckedNodes[i];
node.Checked = false;
}

The CheckedNodes.Count variable is re-evaluated on each pass. So just keep clearing the check box at the 0 index.
int tvCT;
tvCT = TreeView1.CheckedNodes.Count;
if (tvCT > 0)
{
for (int i = 0; i < tvCT; i++)
{
TreeNode node = TreeView1.CheckedNodes[0];
node.Checked = false;
}
}

while (TreeView1.CheckedNodes.Count > 0)
{
TreeView1.CheckedNodes[0].Checked = false;
}
This is a pretty simple block that works for me.

foreach (TreeNode node in TreeView1.Nodes)
{
node.Checked = false;
foreach (TreeNode item1 in node.ChildNodes)
{
item1.Checked = false;
foreach (TreeNode item2 in item1.ChildNodes)
{
item2.Checked = false;
}
}
}
Check it.....! it's work

Related

get sibling controls

Is there some way to find sibling controls / or sibling activity?
In ASP.NET I found a solution by user md1337 solution's, but for WF4 I can't find it.
Thanks a lot.
public static IEnumerable<T> FindVisualChildren<T>(System.Windows.DependencyObject depObj) where T : System.Windows.DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
System.Windows.DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
And in mi Create Activity method I do:
foreach (TextBlock tb in RulesDll.ObjectsClass.FindControls.FindVisualChildren<TextBlock>(target))
{
string a = tb.Text;
}

checkbox list check only limited items

I have a list of check boxes and I want to have an upper limit for you many you can check.
Here is what i have done.
int numSelected = 0;
foreach (ListItem li in chkMultiBrand.Items)
{
if (li.Selected)
{
numSelected = numSelected + 1;
}
}
for (int i = 0; i < chkMultiBrand.Items.Count; i++)
{
if (numSelected >= Convert.ToInt32(objLimit.UPPERLIMIT))
{
chkMultiBrand.Items[i].Selected = false;
}
}
I assume if the max number has been exceeded you want to uncheck the last box that was checked so this should work
public void chk_SelectedIndexChanged(object sender, EventArgs e)
{
int numSelected = 0;
foreach (ListItem li in chkMultiBrand.Items)
{
if (li.Selected)
{
numSelected = numSelected + 1;
}
}
if (numSelected >= Convert.ToInt32(objLimit.UPPERLIMIT))
{
string[] control = Request.Form.Get("__EVENTTARGET").Split('$');
int index = control.Length - 1;
ListItem lastChecked = (ListItem) chkMultiBrand.Items[Int32.Parse(control[index])];
lastChecked.Selected = false;
}
}
Although I would possibly try to do this client side if possible - something like this http://jsfiddle.net/CXfgS/2/
If Im reading this correctly as your code stands what yours doing is
Counting the number of checked boxes in the whole list
If the number from the prvious count is greater than the max allowed set everything to false
You need to combine the loops - this isn't perfect as it doesn't track the order in which the items are selected so only the first X number of checkboxes will remain checked and any subsequent items will be unselected.
int numSelected = 0;
foreach (ListItem li in chkMultiBrand.Items)
{
if (numSelected >= Convert.ToInt32(objLimit.UPPERLIMIT))
{
li.Selected = false;
}
if (li.Selected)
{
numSelected = numSelected + 1;
}
}

child nodes in treeview control automatically checked when parent node checked

I'm using TreeView control. Binding values from database with check box.
Nearly three children are there for parent node like
Parent1
child1
child2
child3
Parent2
child1
child2
child3
I can able to bind data which is from 3 tables all are working well. I want a facility when a parent node checks all its corresponding child automatically get checked.If I click on parent 1 ,child 123 get checked. If I check child1, child2 and child3 get checked. If I check child 2 all child 3 items get checked. How to do that?
Thanks in Advance
Amrutha
The javascript function below can be used to check all child nodes if the parent is checked and check parent node if at least one child node is checked otherwise it is unchecked:
function OnTreeClick(evt) {
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
var t = GetParentByTagName("table", src);
if (isChkBoxClick) {
var parentTable = GetParentByTagName("table", src);
var nxtSibling = parentTable.nextSibling;
if (nxtSibling && nxtSibling.nodeType == 1) {
if (nxtSibling.tagName.toLowerCase() == "div") {
CheckUncheckChildren(parentTable.nextSibling, src.checked);
}
}
CheckUncheckParents(src, src.checked);
}
}
function CheckUncheckChildren(childContainer, check) {
var childChkBoxes = childContainer.getElementsByTagName("input");
var childChkBoxCount = childChkBoxes.length;
for (var i = 0; i < childChkBoxCount; i++) {
childChkBoxes[i].checked = check;
}
}
function CheckUncheckParents(srcChild, check) {
var parentDiv = GetParentByTagName("div", srcChild);
var parentNodeTable = parentDiv.previousSibling;
if (parentNodeTable) {
var checkUncheckSwitch;
var isAllSiblingsChecked = AreAllSiblingsChecked(srcChild);
if (isAllSiblingsChecked) {
checkUncheckSwitch = true;
}
else {
checkUncheckSwitch = false;
}
var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
if (inpElemsInParentTable.length > 0) {
var parentNodeChkBox = inpElemsInParentTable[0];
parentNodeChkBox.checked = checkUncheckSwitch;
CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
}
}
}
function AreAllSiblingsChecked(chkBox) {
var parentDiv = GetParentByTagName("div", chkBox);
var childCount = parentDiv.childNodes.length;
var k = 0;
for (var i = 0; i < childCount; i++) {
if (parentDiv.childNodes[i].nodeType == 1) {
if (parentDiv.childNodes[i].tagName.toLowerCase() == "table") {
var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
//if any of sibling nodes are not checked, return false
if (prevChkBox.checked) {
//add each selected node one value
k = k + 1;
}
}
}
}
//Finally check any one of child node is select if selected yes then return ture parent node check
if (k > 0) {
return true;
}
else {
return false;
}
}
function GetParentByTagName(parentTagName, childElementObj) {
var parent = childElementObj.parentNode;
while (parent.tagName.toLowerCase() != parentTagName.toLowerCase()) {
parent = parent.parentNode;
}
return parent;
}
I used this javascript to solve my problem.
A simple recursive function could do that.
private bool checkTreeNodes(TreeNodeCollection nodes, bool parentChecked)
{
var isChecked = parentChecked;
foreach (TreeNode node in nodes)
{
if (node.Checked || parentChecked)
{
checkTreeNodes(node.Nodes, true);
node.Checked = true;
isChecked = true;
}
else
{
node.Checked = checkTreeNodes(node.Nodes, false);
isChecked = isChecked || node.Checked;
}
}
return isChecked;
}
use it like:
checkTreeNodes(myTree.Nodes, false);

In AS3/Flex, how can I get from flat data to hierarchical data?

I have some data that gets pulled out of a database and mapped to an arraycollection. This data has a field called parentid, and I would like to map the data into a new arraycollection with hierarchical information to then feed to an advanced data grid.
I think I'm basically trying to take the parent object, add a new property/field/variable of type ArrayCollection called children and then remove the child object from the original list and clone it into the children array? Any help would be greatly appreciated, and I apologize ahead of time for this code:
private function PutChildrenWithParents(accountData : ArrayCollection) : ArrayCollection{
var pos_inner:int = 0;
var pos_outer:int = 0;
while(pos_outer < accountData.length){
if (accountData[pos_outer].ParentId != null){
pos_inner = 0;
while(pos_inner < accountData.length){
if (accountData[pos_inner].Id == accountData[pos_outer].ParentId){
accountData.addItemAt(
accountData[pos_inner] + {children:new ArrayCollection(accountData[pos_outer])},
pos_inner
);
accountData.removeItemAt(pos_outer);
accountData.removeItemAt(pos_inner+1);
}
pos_inner++;
}
}
pos_outer++;
}
return accountData;
}
I had a similar problem with a hierarchical task set which was slightly different as it has many root elements, this is what i did, seems good to me:
public static function convertFlatTasks(tasks:Array):Array
{
var rootItems:Array = [];
var task:TaskData;
// hashify tasks on id and clear all pre existing children
var taskIdHash:Array = [];
for each (task in tasks){
taskIdHash[task.id] = task;
task.children = [];
task.originalChildren = [];
}
// loop through all tasks and push items into their parent
for each (task in tasks){
var parent:TaskData = taskIdHash[task.parentId];
// if no parent then root element, i.e push into the return Array
if (parent == null){
rootItems.push(task);
}
// if has parent push into children and originalChildren
else {
parent.children.push(task);
parent.originalChildren.push(task);
}
}
return rootItems;
}
Try this:
AccountData:
public class AccountData
{
public var Id:int;
public var ParentId:int;
public var children:/*AccountData*/Array;
public function AccountData(id:int, parentId:int)
{
children = [];
this.Id = id;
this.ParentId = parentId;
}
}
Code:
private function PutChildrenWithParents(accountData:ArrayCollection):AccountData
{
// dummy data for testing
//var arr:/*AccountData*/Array = [new AccountData(2, 1),
// new AccountData(1, 0), // root
// new AccountData(4, 2),
// new AccountData(3, 1)
// ];
var arr:/*AccountData*/Array = accountData.source;
var dict:Object = { };
var i:int;
// generate a lookup dictionary
for (i = 0; i < arr.length; i++)
{
dict[arr[i].Id] = arr[i];
}
// root element
dict[0] = new AccountData(0, 0);
// generate the tree
for (i = 0; i < arr.length; i++)
{
dict[arr[i].ParentId].children.push(arr[i]);
}
return dict[0];
}
dict[0] holds now your root element.
Maybe it's doesn't have the best possible performance but it does what you want.
PS: This code supposes that there are no invalid ParentId's.
Here's what I ended up doing, apparently you can dynamically add new properties to an object with
object['new_prop'] = whatever
From there, I used a recursive function to iterate through any children so you could have n levels of the hierarchy and if it found anything it would pass up through the chain by reference until the original function found it and acted on it.
private function PutChildrenWithParents(accountData : ArrayCollection) : ArrayCollection{
var pos_inner:int = 0;
var pos_outer:int = 0;
var result:Object = new Object();
while(pos_outer < accountData.length){
if (accountData[pos_outer].ParentId != null){
pos_inner = 0;
while(pos_inner < accountData.length){
result = CheckForParent(accountData[pos_inner],
accountData[pos_outer].ParentId);
if ( result != null ){
if(result.hasOwnProperty('children') == false){
result['children'] = new ArrayCollection();
}
result.children.addItem(accountData[pos_outer]);
accountData.removeItemAt(pos_outer);
pos_inner--;
}
pos_inner++;
}
}
pos_outer++;
}
return accountData;
}
private function CheckForParent(suspectedParent:Object, parentId:String) : Object{
var parentObj:Object;
var counter:int = 0;
if ( suspectedParent.hasOwnProperty('children') == true ){
while (counter < suspectedParent.children.length){
parentObj = CheckForParent(suspectedParent.children[counter], parentId);
if (parentObj != null){
return parentObj;
}
counter++;
}
}
if ( suspectedParent.Id == parentId ){
return suspectedParent;
}
return null;
}

Cannot add an entity that already exists

Code:
public ActionResult Create(Group group)
{
if (ModelState.IsValid)
{
group.int_CreatedBy = 1;
group.dtm_CreatedDate = DateTime.Now;
var Groups = Request["Groups"];
int GroupId = 0;
GroupFeature GroupFeature=new GroupFeature();
foreach (var GroupIdd in Groups)
{
// GroupId = int.Parse(GroupIdd.ToString());
}
var Features = Request["Features"];
int FeatureId = 0;
int t = 0;
int ids=0;
string[] Feature = Features.Split(',').ToArray();
//foreach (var FeatureIdd in Features)
for(int i=0; i<Feature.Length; i++)
{
if (int.TryParse(Feature[i].ToString(), out ids))
{
GroupFeature.int_GroupId = 35;
GroupFeature.int_FeaturesId = ids;
if (ids != 0)
{
GroupFeatureRepository.Add(GroupFeature);
GroupFeatureRepository.Save();
}
}
}
return RedirectToAction("Details", new { id = group.int_GroupId });
}
return View();
}
I am getting an error here Cannot add an entity that already exists. at this line GroupFeatureRepository.Add(GroupFeature);
GroupFeatureRepository.Save();
This line:
GroupFeature GroupFeature=new GroupFeature();
needs to be inside your for loop, like this:
for(int i=0; i<Feature.Length; i++)
{
if (int.TryParse(Feature[i].ToString(), out ids))
{
GroupFeature GroupFeature=new GroupFeature();
You need to add a new GroupFeature each time(e.g. one not in that collection, which your re-used object already is after the first loop). You can't re-use the same GroupFeature object like that for adding, but moving it inside the loop so you generate a distinct GroupFeature each time will resolve this.

Resources