拆分一个字符串并添加到DataGridView

时间:2018-05-22 20:10:54

标签: .net vb.net

我有一个像这样的字符串:

"{[Entry Number: 1 | @AppUser: James | @AppTimeDate: 5/21/2018 | @AppText: A lot of multiline text here]}{[Entry Number: 2 | @AppUser: John | @AppTimeDate: 5/22/2018 | @AppText: More multiline text here]}"

我希望将此字符串放入DataGridView中,如下所示:

------------------------------
|Name     |Text              | -This is the header
------------------------------
|James    |A lot of multiline| -This is all one row for James
|5/21/2018|text here         |
------------------------------
|John     |More multiline    | -This is all another row for John
|5/21/2018|text here         |
------------------------------

有人能为我提供一个如何实现这一目标的例子吗?我做了很多谷歌搜索,但我似乎无法找到一个如何实现这样的事情的例子。



到目前为止我已经尝试过这样做,但我一直收到“System.Reflection.TargetInvocationException”错误:

Dim RawNote As String = txtNotes.Text
Dim Splitter As String = "{[Entry Number: "

Dim substrings() As String = Regex.Split(RawNote, Splitter)
For Each match As String In substrings
    MsgBox(match)
Next

2 个答案:

答案 0 :(得分:1)

我的代码出错了;但是我对Regex并不熟悉。一个简单的String.Split将完成同样的事情。我使用的.Split重载采用Sting数组。我们只需要一个1元素的数组。数组在Dim语句中初始化。第二个参数是必要的。有了这个开始,也许你可以做其余的事。

Private Sub ParseString()
        Dim RawNote As String = "{[Entry Number: 1 | @AppUser: James | @AppTimeDate: 5/21/2018 | @AppText: A lot of multiline text here]}{[Entry Number: 2 | @AppUser: John | @AppTimeDate: 5/22/2018 | @AppText: More multiline text here]}"
        Dim Splitter() As String = {"{[Entry Number: "}
        Dim substrings() As String = RawNote.Split(Splitter, StringSplitOptions.RemoveEmptyEntries)
        For Each match As String In substrings
            MsgBox(match)
        Next
End Sub

答案 1 :(得分:-1)

使用Linq,请执行以下步骤:

  • 将输入字符串拆分为不同的Entries
  • 消除无用的文字部分
  • 拆分每个条目以提取其元素列表(Fields
  • 删除未使用的文字部分(@AppText@AppTimeDate等)。
  • 使用指定的格式生成新的字符串数组
  • 将字符串数组添加到DataGridView行

注意:
此代码假设已经设置了 DataGridView ,其中包含两个文本列

Dim RawNote As String = "{[Entry Number: 1 | @AppUser: James | @AppTimeDate: 5/21/2018 | @AppText: A lot of multiline text here]}" &
                        "{[Entry Number: 2 | @AppUser: John | @AppTimeDate: 5/22/2018 | @AppText: More multiline text here]}"

Dim InputList As List(Of String()) =
        RawNote.Split(New String() {"]}{["}, StringSplitOptions.None).
                Select(Function(part) part.Replace("{[", "").Replace("]}", "")).
                Select(Function(elm) elm.Split("|"c).
                                         Select(Function(str) str.Remove(0, str.IndexOf(":"c) + 1)).
                                         Skip(1).ToArray()).
                Select(Function(f) New String() {f(0) + Environment.NewLine + f(1), f(2)}).ToList()

DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells

For Each row As String() In InputList
    DataGridView1.Rows.Add(row)
Next

结果如下:

enter image description here