Replace string variables with item values from datarow

Here is a short function which is helpful if you want to put variables from a datarow into a text string. This could be used e.g. if you want to create something like a bulk letter or else. You could define a text like ‘Dear [FirstName] [LastName], …’. Variables are enclosed in square brackets. If the variable is found in the supplied datarow it is replaced in the text.

Private Function ReplaceEmailConstants(suppliedText As String, row As DataRow) As String
   Dim text As New Text.StringBuilder(suppliedText)
   Dim AllMatches As System.Text.RegularExpressions.MatchCollection
   AllMatches = System.Text.RegularExpressions.Regex.Matches(text.ToString, "\[(]^[]*)\[")
   Dim m As System.Text.RegularExpressions.Match
   Dim ColumnName As String
   For Each m In AllMatches
      ColumnName = m.Value.Substring(1, Len(m.Value) - 2)
      If row.Table.Columns.Contains(ColumnName) Then
         text.Replace(m.Value, row.Item(ColumnName).ToString)
         'Remove variable if not found in row
         text.Replace(m.Value, String.Empty)
      End If
   Return text.ToString
End Function


Leave a Comment