如何为 TreeNode Name 和 text 属性设置 MaxLength? [英] How can set MaxLength for TreeNode Name and text property?

查看:35
本文介绍了如何为 TreeNode Name 和 text 属性设置 MaxLength?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为 TreeNode Name 和 text 属性设置 MaxLength?这是一个 windows 窗体应用程序,用户右键单击树视图以添加节点,树节点名称的最大长度应为 40 个字符.目前我在 AfterlabelEdit 事件中检查这个,如果没有则抛出一条消息.字符数超过.但是要求限制长度而不像我们在文本框中那样显示消息框.

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.

谢谢.

推荐答案

您可以在树视图上显示一个文本框并在其上设置 MaxLength.

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;
    }

然后在树状视图 BeforeLabelEdit 中设置文本框的 MaxLength 并将其显示在当前选定的节点上:

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.

这篇关于如何为 TreeNode Name 和 text 属性设置 MaxLength?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆