Reputation: 161
Domain\X_User|X_User,Domain\Y_User|Y_User,
I'm using a SSRS report and I'm receiving the value on the above pattern ( it may contain any number of users), i tried to write a visual basic function in the report body ( Custom code) to split the above string and return the following value:
X_User,Y_User
I tried to write this code inside the report body
Public Function SubString_Owner(X As String) As String
Dim OwnerArray() As String = Split(X, ",")
Dim Names As String
Dim i As Integer = 0
While i <= OwnerArray.Length - 1
Dim NamesArr As String() = Split(OwnerArray(0), "|")
Names = NamesArr(1) + ","
i += 1
End While
Return Names
End Function
the problem is when trying to split OwnerArray(i) using the index, it gives an error but when using a fixed value like "zero" OwnerArray(0), it build fine, any one can figure out why is this ??
Upvotes: 0
Views: 5364
Reputation: 404
Does the string end in a comma, like the example string that you put up?
Cause if that is the case, that's your problem right there.
Your first split then creates an array with 3 indexes
{"Domain\X_User|X_User", "Domain\Y_User|Y_User", ""}
(Note the empty string in index 2)
If you then going to loop the array you go through it 3 times, the splits there work just fine for index 0 and 1, resulting in {"Domain\X_User", "X_User"} and {"Domain\Y_User", "Y_User"}, but splitting the 3rd index, the result of your split is an empty array.
When you try to retrieve the 2nd index of the NamesArr array, it'll result in an IndexOutOfRangeExeption.
You better ad some kind of check within the loop to make sure you can actually split your value:
Public Function SubString_Owner(X As String) As String
Dim OwnerArray() As String = Split(X, ",")
Dim Names As String
Dim i As Integer = 0
While i <= OwnerArray.Length - 1
If Not String.IsNullOrEmpty(OwnerArray(i)) AndAlso OwnerArray(i).Contains("|") Then
Dim NamesArr As String() = Split(OwnerArray(i), "|")
Names &= NamesArr(1) & ","
End If
i += 1
End While
Return Names
End Function
I'm doing 2 checks here, the first to make sure that the provided value isn't Nothing (null) and the 2nd to see if it contains the needed "|" to split it. The 2nd statement would give a NullReference error if the value would be Nothing.
Also note that I edited the line
Names = NamesArr(1) + ","
into
Names &= NamesArr(1) & ","
Your statement would overwrite Names with every loop and you would only return the last username. Also to concatenate string in VB.NET, you should use "&" instead of "+"
Oh and why haven't you used a FOR loop? It's more readable than a While loop and therefor preferred in this case.
Upvotes: 1