Archive Browser
Download CustomTreeViewLabelEditPart2.zip, last updated 28/10/2013 (14.07 KB)
Download- md5: 84276c0e1d02b4750fc1ecd76d71bedd
using System;
using System.Windows.Forms;
namespace CustomTreeViewLabelEdit
{
internal partial class MainForm : Form
{
// Extending the LabelEdit functionality of a TreeView to include validation
// http://cyotek.com/blog/extending-the-labeledit-functionality-of-a-treeview-to-include-validation
#region Constructors
public MainForm()
{
InitializeComponent();
}
#endregion
#region Overridden Members
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.FillTree(subclassedTreeView);
}
#endregion
#region Members
private void FillTree(TreeView treeView)
{
TreeNode root;
Random random;
random = new Random();
treeView.BeginUpdate();
root = new TreeNode
{
Name = "Alpha",
Text = "Alpha",
};
foreach (string name in new[]
{
"Beta", "Gamma", "Delta", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi", "Rho", "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega"
})
{
string value;
int imageIndex;
imageIndex = random.Next(0, imageList.Images.Count);
value = name.GetHashCode().ToString("X2");
root.Nodes.Add(new TreeNode
{
Text = string.Format("{0}: {1}", name, value),
Name = name,
Tag = value,
ImageIndex = imageIndex,
SelectedImageIndex = imageIndex
});
}
treeView.Nodes.Add(root);
root.Expand();
treeView.EndUpdate();
}
#endregion
#region Event Handlers
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void renameToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeView treeView;
treeView = this.ActiveControl as TreeView;
if (treeView != null && treeView.SelectedNode != null)
treeView.SelectedNode.BeginEdit();
}
private void subclassedTreeView_RequestDisplayText(object sender, NodeRequestTextEventArgs e)
{
e.Node.Name = e.Label;
e.Label = string.Format("{0}: {1}", e.Label, e.Node.Tag);
}
private void subclassedTreeView_RequestEditText(object sender, NodeRequestTextEventArgs e)
{
e.Label = e.Node.Name;
}
private void subclassedTreeView_ValidateLabelEdit(object sender, NodeLabelEditEventArgs e)
{
TreeNode[] matchingNodes;
// Check to make sure the value the user enters isn't used by any other node than the current.
// This code assumes that all names in the tree are unique, regardless of level
matchingNodes = subclassedTreeView.Nodes.Find(e.Label, true);
if (matchingNodes.Length != 0 && matchingNodes[0] != e.Node)
{
MessageBox.Show("You must enter a unique value.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
e.CancelEdit = true;
}
}
#endregion
}
}
Donate
This software may be used free of charge, but as with all free software there are costs involved to develop and maintain.
If this site or its services have saved you time, please consider a donation to help with running costs and timely updates.
Donate