Search code examples
asp.netdatabasevb.netdatatablesqlconnection

How can I create this column in my datatable with the concatenated two values, separated with a dash?


I'm using Visual Studio with asp.net, vb.net, and webforms. I am trying to concatenate each RoleDescription and FirstName and add them into a new column on my datatable.

This line Dim RoleNameConcat = sdr.GetValue("RoleDescription") + " - " + sdr.GetValue("firstname") throws the error

System.FormatException: Input string was not in a correct format.

How can I create this column in my datatable with the concatenated two values, separated with a dash?


Solution

  • Populate your table first, then add the column with its Expression property set to automatically populate it from the other two:

    Dim table As New DataTable
    
    '...
    
    Using reader = command.ExecuteReader()
        table.Load(reader)
    End Using
    
    '...
    
    table.Columns.Add("RoleDescriptionAndFirstName",
                      GetType(String),
                      "RoleDescription + ' - ' + FirstName")
    

    Done! The column itself will perform the concatenation and any changes to the data in the other columns will be automatically propagated to the new column too.