问题
How can set MaxLength for TreeNode Name and text property? This is a windows forms application, where user right clicks a treeview to add a node and the maxlength of the treenode name should be 40 chars. Currently I check this in AfterlabelEdit event, and throw a message if no. of chars exceeds. But the requiremnet says to limit the length without showing the message box as we do in textboxes.
Thanks.
回答1:
You could display a text box over the treeview and set the MaxLength on that.
One way to do that is create a text box with the form:
private TextBox _TextBox;
public Form1()
{
InitializeComponent();
_TextBox = new TextBox();
_TextBox.Visible = false;
_TextBox.LostFocus += new EventHandler(_TextBox_LostFocus);
_TextBox.Validating += new CancelEventHandler(_TextBox_Validating);
this.Controls.Add(_TextBox);
}
private void _TextBox_LostFocus(object sender, EventArgs e)
{
_TextBox.Visible = false;
}
private void _TextBox_Validating(object sender, CancelEventArgs e)
{
treeView1.SelectedNode.Text = _TextBox.Text;
}
Then in the tree view BeforeLabelEdit set the MaxLength of the text box and show it over the currently selected Node:
private void treeView1_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
{
_TextBox.MaxLength = 10;
e.CancelEdit = true;
TreeNode selectedNode = treeView1.SelectedNode;
_TextBox.Visible = true;
_TextBox.Text = selectedNode.Text;
_TextBox.SelectAll();
_TextBox.BringToFront();
_TextBox.Left = treeView1.Left + selectedNode.Bounds.Left;
_TextBox.Top = treeView1.Top + selectedNode.Bounds.Top;
_TextBox.Focus();
}
You'll probably want to add some additional functionality to the text box so it sizes correctly based on the width of the tree view and also so it accepts the new text on the user hitting return, etc.
来源:https://stackoverflow.com/questions/1298228/how-can-set-maxlength-for-treenode-name-and-text-property