C#从文本文件/显示到列表视图中查找特定行

时间:2019-02-16 18:26:20

标签: c# listview substring

以下是步骤: 1.浏览到文本文件 2.将文本加载到文本框中 3.从文本中找到特定的行/位置 4.在3列的LISTVIEW中显示。

我现在的操作方式是这样:

listview1.Items.Add(new ListViewItem(new[] { "1", "Type", text1.Substring(0, 12) }));

listview1.Items.Add(new ListViewItem(new[] { "2", "ID", text1.Substring(13, 2) }));

listview1.Items.Add(new ListViewItem(new[] { "3", "Name", text1.Substring(15, 3) }));

listview1.Items.Add(new ListViewItem(new[] { "4", "DOB", text1.Substring(17, 2) }));

listview1.Items.Add(new ListViewItem(new[] { "5", "Version", text1.Substring(18, 7) }));

它正在工作...。直到我遇到一个长度小于我的子字符串代码的文本文件。我崩溃了(OutOfRangeException)

我想知道是否有更好的编码方式。如果没有,那么解决OutOfRangeExceptiion错误的最佳方法是什么。

作为一种变通方法,我正在执行text1.padright(999)来增加我加载的任何文本文件的长度。但是可能有更好的解决方案。

谢谢!

1 个答案:

答案 0 :(得分:0)

我建议添加这样的扩展方法:

public static class Ext 
{
    public static string SubstringWithCheck(this string text, int start, int length, string replace = "")
    {
        if (text.Length < start + length)
        {
            return replace;
        }
        return text.Substring(start, length);
    }
}

然后您可以使用此方法:

listview1.Items.Add(new ListViewItem(new[] { "1", "Type", text1.SubstringWithCheck(0, 12) }));

或者这样:

listview1.Items.Add(new ListViewItem(new[] { "1", "Type", text1.SubstringWithCheck(0, 12, "your text here") }));
相关问题