c#使用richtextbox中的项目填充listview(每行放入列,打破空行并进入下一行)

c#使用richtextbox中的项目填充listview(每行放入列,打破空行并进入下一行)

问题描述:

我想通读richtextbox,将每个段落连同段落中的每一行其专栏。c#使用richtextbox中的项目填充listview(每行放入列,打破空行并进入下一行)

richtextbox example

我想有3列:

段落以一个空行

在下面在RichTextBox的信息的示例分离。 然后段落中的每个前两行将在前两列中,然后将所有剩余行放入第三列中。

我现在所拥有的就是它将每列3列读入如下所示的listview,这显然没有达到我想要的。

for (int i = 0; i < richTextBox1.Lines.Count(); i += 3) 
    { 
     listView1.Items.Add(new ListViewItem(new[]{ 
      richTextBox1.Lines[i], 
      richTextBox1.Lines[i+1], 
      richTextBox1.Lines[i+2]]})); 
    } 

//Add this method 


    public static HashSet<Tuple<int, string, string, string>> GetRichTextBoxSections(string[] Lines) 
     { 
      HashSet<Tuple<int, string, string, string>> Sections = new HashSet<Tuple<int, string, string, string>>(); 
      int SectionNumber = -1; 
      int SectionIndexLineNumber = 0; 
      bool FoundNewSectionNumber = false; 
      string Col1 = string.Empty; 
      string Col2 = string.Empty; 
      string Col3 = string.Empty; 
      int LinesCount = Lines.Length; 
      for (int i = 0; i < LinesCount; i++) 
      { 

       string NoSpaces = System.Text.RegularExpressions.Regex.Replace(Lines[i], @"\s+", ""); 
       if (FoundNewSectionNumber == false) 
       { 
        SectionIndexLineNumber = i; 
       } 



       if (FoundNewSectionNumber) 
       { 
        if (string.IsNullOrWhiteSpace(NoSpaces) || string.IsNullOrEmpty(NoSpaces) & FoundNewSectionNumber == true) 
        { 

         Sections.Add(new Tuple<int, string, string, string>(SectionNumber, Col1, Col2, Col3)); 
         SectionNumber = -1; 
         FoundNewSectionNumber = false; 
         Col1 = string.Empty; 
         Col2 = string.Empty; 
         Col3 = string.Empty; 
         SectionIndexLineNumber = 0; 
         continue; 

        } 
        else 
        { 
         switch (i - SectionIndexLineNumber) 
         { 
          case 1: 
           Col1 = Lines[i]; 
           break; 
          case 2: 
           Col2 = Lines[i]; 
           break; 
          default: 
           Col3 += Lines[i]; 
           break; 
         } 
        } 
       } 
       if (FoundNewSectionNumber == false) 
       { 
        FoundNewSectionNumber = int.TryParse(NoSpaces, out SectionNumber); 
       } 
       if (i == (LinesCount - 1)) 
       { 
        Sections.Add(new Tuple<int, string, string, string>(SectionNumber, Col1, Col2, Col3)); 
       } 
      } 
      return Sections; 
     } 

这样称呼它下面

foreach(Tuple<int,string,string,string> SectionData in GetRichTextBoxSections(richTextBox1.Lines)) 
      { 

listView1.Items.Add(new ListViewItem(new[]{ 
//Item1 is the section index if you need it 
      SectionData.Item2, 
      SectionData.Item3, 
      SectionData.Item4})); 
} 
+0

嗨@loannis G.谢谢.....但是当我尝试运行该程序,我得到这个错误。 “foreach语句无法对'void'类型的变量进行操作,因为'void'不包含'GetEnumerator'的公共定义。” – BiKe

+0

立即尝试......替换为刚添加的新变量。 \t 我以前改过它,但忘记点击保存,让我知道如果它是好的 –

+0

好的,现在的错误。谢谢。然而,第一行永远不会是一个整数,是的,我想将它包含在列表视图中。我们怎样才能使得只有整数,而字符串呢? – BiKe