C C
C C

Reputation: 1

LEN function not returning a value in VB.NET

With the following code segment the Strings.Len() function is being skipped or not returning a value since the debugger says the variable Test1 is not assigned while the following line with Strings.InStr() function works properly:

   sOPCTagItem = opcTagItem.Cells.Value --> assigns "DO1001_Inp_IOFault"    
   sBaseTagItemName = Left(sOPCTagItem, InStr(sOPCTagItem, "_") - 1) --> assigns "DO1001"

   iTest1 = Len(sOPCTagItem)  --> = nothing assigned
   iTest2 = InStr(sOPCTagItem, "_") --> = 7
   iTest1 = iTest1 - iTest2   --> = nothing assigned
   sBaseTagItemExtension = Right(sOPCTagItem, Len(sOPCTagItem) - InStr    (sOPCTagItem, "_"))   --> = nothing assigned

Upvotes: 0

Views: 761

Answers (2)

the_lotus
the_lotus

Reputation: 12748

It's weird that they return nothing since their return value is an integer. I would try using the proper String method.

    iTest1 = sOPCTagItem.Length
    iTest2 = sOPCTagItem.IndexOf("_")
    iTest1 = iTest1 - iTest2
    sBaseTagItemExtension = sOPCTagItem.Substring(sOPCTagItem.Length - sOPCTagItem.IndexOf("_"))

Upvotes: 0

Andrew Mortimer
Andrew Mortimer

Reputation: 2370

Both of these methods work for your scenario. They will depend on your input data and the consistency of underscore delimiters in your data.

You may just be missing Option Explicit On

Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
    Debug.Print(getBaseTagItem("DO1001_Inp_IOFault"))
    Debug.Print(getBaseTagItemOldSchool("DO1001_Inp_IOFault"))
End Sub

Private Function getBaseTagItem(tagItem As String)

    Dim vals() As String = tagItem.Split("_"c)
    Return String.Concat(vals(1), "_", vals(2))

End Function

Private Function getBaseTagItemOldSchool(tagItem As String)

    Dim sOPCTagItem As String = tagItem
    Dim sBaseTagItemName As String = Strings.Left(sOPCTagItem, InStr(sOPCTagItem, "_") - 1)

    Dim iTest1 As Integer = Len(sOPCTagItem)
    Dim iTest2 As Integer = InStr(sOPCTagItem, "_")
    iTest1 = iTest1 - iTest2
    Dim sBaseTagItemExtension As String = Strings.Right(sOPCTagItem, Len(sOPCTagItem) - InStr(sOPCTagItem, "_"))
    Return sBaseTagItemExtension

End Function

Upvotes: 1

Related Questions