如何拆分特定格式字符串并导入DataGridView?遇TargetInvocationException报错
Hey there, let's tackle this problem step by step. That System.Reflection.TargetInvocationException you're hitting is almost certainly from unreliable string splitting leading to invalid data handling later on (even if your current code only uses MsgBox, the issue would blow up once you try binding to DataGridView). Let's build a robust solution to parse your string and bind it to a DataGridView correctly.
First, create a simple class to represent each note entry—this makes binding to DataGridView straightforward and type-safe:
Public Class NoteEntry Public Property EntryNumber As Integer Public Property AppUser As String Public Property AppTimeDate As Date Public Property AppText As String End Class
Your original string uses {[...]} to wrap each entry, with fields separated by |. Manual splitting with a fixed string is error-prone (e.g., empty substrings from the start of the string), so we'll use regex to reliably extract each entry first, then parse the fields inside.
Here's the complete parsing and binding code (add this to your form's code):
Imports System.Text.RegularExpressions Imports System.ComponentModel Private Sub LoadNotesIntoDataGridView() Dim rawNoteText As String = txtNotes.Text Dim noteEntries As New BindingList(Of NoteEntry)() ' BindingList lets DataGridView auto-update if entries change ' Match all entries wrapped in {[...]} Dim entryMatches As MatchCollection = Regex.Matches(rawNoteText, "\{\[(.*?)\]\}") For Each entryMatch As Match In entryMatches ' Extract the content inside {[ and ]} Dim entryContent As String = entryMatch.Groups(1).Value ' Split fields using " | " as the separator, ignoring empty entries Dim fields() As String = entryContent.Split(New String() {" | "}, StringSplitOptions.RemoveEmptyEntries) Dim newEntry As New NoteEntry() For Each field As String In fields ' Split each field into key and value—limit to 2 splits to handle colons in AppText Dim keyValuePair() As String = field.Split(New String() {": "}, 2) If keyValuePair.Length = 2 Then Select Case keyValuePair(0).Trim() Case "Entry Number" ' Use TryParse to avoid crashes if the number is invalid Integer.TryParse(keyValuePair(1).Trim(), newEntry.EntryNumber) Case "@AppUser" newEntry.AppUser = keyValuePair(1).Trim() Case "@AppTimeDate" Date.TryParse(keyValuePair(1).Trim(), newEntry.AppTimeDate) Case "@AppText" newEntry.AppText = keyValuePair(1).Trim() End Select End If Next noteEntries.Add(newEntry) Next ' Bind the list to DataGridView DataGridView1.DataSource = noteEntries ' Optional: Customize column headers for better readability With DataGridView1 .Columns("EntryNumber").HeaderText = "Entry Number" .Columns("AppUser").HeaderText = "User" .Columns("AppTimeDate").HeaderText = "Date & Time" .Columns("AppText").HeaderText = "Note Content" ' Enable row auto-sizing to fit multiline AppText .AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells End With End Sub
That TargetInvocationException was likely caused by:
- The regex split using
"{[Entry Number: "creating an empty first substring (since your string starts with that exact sequence) - No error handling for invalid data (e.g., if a field is missing or formatted incorrectly)
- Not accounting for potential special characters in
AppText(like colons or pipes) that would break simple splitting
The code above fixes all these issues by:
- Using regex to only capture valid full entries
- Limiting field splits to 2 parts to preserve colons in the note text
- Using
TryParseto avoid crashes from invalid number/date values - Using
BindingListfor seamless DataGridView binding
Just call LoadNotesIntoDataGridView() (e.g., from a button click event) after pasting your original string into txtNotes. Your DataGridView will display each entry as a row, with multiline note text properly wrapped and visible.
内容的提问来源于stack exchange,提问作者Jason Mills

