【问题标题】:Limiting the maximum text length of ListViewItem?限制 ListViewItem 的最大文本长度?
【发布时间】:2012-04-04 07:08:24
【问题描述】:

我在基于 C# 的 win-form 项目中有一个 ListView。是否可以限制 ListView 内所有 ListViewItem 标题的最大长度?

更新

我的意思是输入长度,我把item设置为editable,这样用户就可以重命名item了

更新2

对,它被称为该项目的“文本”,而不是标题。

【问题讨论】:

  • 是的...您确实可以控制进入 ListView 的内容,不是吗?因此,请不要允许任何标题超过您的最大值的项目。还是我误解了你的问题?

标签: c# listview listviewitem


【解决方案1】:

您可以使用列表视图的label after edit event。这是一个示例。

private void listview1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
    try
    {
        const int maxPermittedLength = 1;

        if (e.Label.Length > maxPermittedLength)
        {
            //trim text
            listview1.Items[e.Item].SubItems[0].Text = listview1.Items[e.Item].SubItems[0].Text.Substring(0, maxPermittedLength); //or something similar

            //or

            //show a warning message

            //or

            e.CancelEdit = true; //cancel the edit
        }
    }
    catch (Exception ex)
    {

    }
}

请记住,它很棘手,并不简单,您将不得不处理一些异常,但那是功课.. 上面的代码不是有效的代码,但您现在知道如何去做了。仔细阅读文档,它有一个很好的示例和与此事件相关的警告。

【讨论】:

    【解决方案2】:

    ListViewItem 的标题是什么意思?你的意思是项目文本吗?我相信任何可回收的东西都是可修复和可控的。如果是item text,可以写个check方法

    public string SimplifyTxt(string input)
    {
        if(input.Length>LIMIT_NUMBER)
        {
           //please shorten the string before display
        }
        return retStr;
    }
    

    然后可以将其分配为

    listview1.items.add(new Listviewitem{Text=retVal});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      相关资源
      最近更新 更多