Turning On Checkboxes For A TreeView


	MyTreeView->CheckBoxes = true;

Showing Checkboxes only for certain nodes

This isn't a feature of TreeView, but can easily be created by using images – see below…

Using images for tree view nodes (e.g. checkboxes only for some nodes)

Add an image list to your form.  Set its ImageSize property to match the size of the images you will add.  Assign it to the tree view:


	MyTreeView->ImageList = MyImageList;

To set the image for a node (you need to do it for selected state also or the image will change when a node is clicked on):


	MyTreeNode->Nodes[0]->ImageIndex = 1;
	MyTreeNode->Nodes[0]->SelectedImageIndex = 1;

Toggle the checked state when a node is clicked:


	private: System::Void MyTreeView_AfterSelect(System::Object^  sender, System::Windows::Forms::TreeViewEventArgs^  e)
	{
		if (MyTreeView->SelectedNode)		//Ensure a node is selected
		{
			if (MyTreeView->SelectedNode->Level == 1)		//0 = root level of any node, 1 1st child level, etc
			{
				//Work out this nodes location within the TreeView
				int NodeIndex = e->Node->Index;
				TreeNode ^ParentTreeNode = e->Node->Parent;
				int ParentIndex = ParentTreeNode->Index;

				//Toggle the checkbox image
				if (MyTreeView->SelectedNode->ImageIndex)
				{
					MyTreeView->SelectedNode->ImageIndex = 0;
					MyTreeView->SelectedNode->SelectedImageIndex = 0;
				}
				else
				{
					MyTreeView->SelectedNode->ImageIndex = 1;
					MyTreeView->SelectedNode->SelectedImageIndex = 1;
				}
			}
			MyTreeView->SelectedNode = nullptr;
		}
	}

 

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *