xrjf 230 Posting Whiz

"Windows PowerShell is a programming language from Microsoft that is primarily designed for system administration. Since PowerShell is built on top of the .NET framework, .NET’s excellent regular expression support is also available to PowerShell programmers."

Now, try using .NET's sequence (?!subexpr) and (?<!subexpr).

(?!subexpr) for ex. \w+\b(?![,:;]) will find a word that is not followed by coma, colon or semicolon

(?<!subexpr) for example (?<!,)\b\w+will find a word that is not preceeded by a coma

xrjf 230 Posting Whiz

I imagine you are aware of SQL injection. If not you may read here about it.

xrjf 230 Posting Whiz

One question: where do you define itemcoll?

xrjf 230 Posting Whiz

Take a look Here

xrjf 230 Posting Whiz

I see tag <asp:Panel in line #9 open but never closed, is it?

xrjf 230 Posting Whiz

Sorry for the inconvient. There were extra lines not needed.

    Sub Main()
        Try
            prependTextToAllLines("Append.txt")
            Console.Write("Process succeeded. Press Enter key to exit.")
            Console.ReadLine()
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
            Console.ReadLine()
        End Try

    End Sub
    Sub prependTextToAllLines(path As String)
        Try
            Dim fsw As New FileStream(path, FileMode.Open, FileAccess.Write, FileShare.Read)
            Dim sw As New StreamWriter(fsw)
            Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            Dim sr As New StreamReader(fs)
            Dim lineNum As Int32 = 1
            Do
                Dim sCurrLn As String = sr.ReadLine
                Dim sPrepend As String = String.Format("Line #{0:0000000} ", lineNum)
                lineNum += 1
                sw.WriteLine(sPrepend + sCurrLn)
            Loop While Not sr.EndOfStream
            sr.Close()
            sw.Close()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
End Module
xrjf 230 Posting Whiz

For some reason I don' t know, yesterday the code was working and today it fails. So, I've rewritten the code and it is:

Sub Main()
    Try
        prependTextToAllLines("Append.txt")
    Catch ex As Exception
        Console.WriteLine(ex.ToString)
        Console.ReadLine()
    End Try

End Sub
Sub prependTextToAllLines(path As String)
    Dim bRet As Boolean = False
    Dim fs As FileStream = Nothing
    Dim fsw As FileStream = Nothing
    Dim sr As StreamReader = Nothing
    Dim sw As StreamWriter = Nothing
    Try
        fsw = New FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)
        sw = New StreamWriter(fsw)
        fs = New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
        sr = New StreamReader(fs)
        Dim lineNum As Int32 = 1
        Dim fileLen As Long = fs.Length
        Dim currBufferLine As Int32 = 0
        Dim EndofBuffer As Int32 = -1
        Dim rdPos As Long = 0
        Dim wrPos As Long = 0
        Do
            Dim sCurrLn As String = sr.ReadLine
            Dim sPrepend As String = String.Format("Line #{0:0000000} ", lineNum)
            lineNum += 1
            sw.WriteLine(sPrepend + sCurrLn)
        Loop While Not sr.EndOfStream
        sr.Close()
        sw.Close()
        bRet = True
    Catch ex As Exception
    End Try
End Sub
xrjf 230 Posting Whiz

@rproffitt: If the file is large and assuming we can buffer a first bunch of lines so that streamreader and streamwriter will never overlap:

        Try
            Dim path As String = "Append.txt"
            Using fs As New FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
                Dim sr As New StreamReader(fs)
                Dim sw As New StreamWriter(fs)
                Dim lineNum As Int32 = 1
                Dim fileLen As Long = fs.Length
                Dim linesToBuffer As Int32 = 3
                Dim currBufferLine As Int32 = 0
                Dim vBuffer(linesToBuffer - 1) As String
                Dim EndofBuffer As Int32 = -1
                Dim rdPos As Long = 0
                Dim wrPos As Long = 0
                For i = 0 To vBuffer.Length - 1
                    vBuffer(i) = sr.ReadLine
                Next
                rdPos = fs.Position
                Do
                    fs.Seek(wrPos, SeekOrigin.Begin)
                    sw.WriteLine(String.Format("Line #{0:0000000} ", lineNum) + vBuffer(currBufferLine))
                    wrPos = fs.Position 
                    ' if wrPos >= rdPos signifies buffer too small'
                    If rdPos < fileLen Then
                        fs.Seek(rdPos, SeekOrigin.Begin)
                        vBuffer(currBufferLine) = sr.ReadLine
                        rdPos += vBuffer(currBufferLine).Length + 2
                        lineNum += 1
                    Else
                        If EndofBuffer = -1 Then
                            sr.Close()
                            EndofBuffer = linesToBuffer
                        End If
                        EndofBuffer -= 1
                        If EndofBuffer < 0 Then Exit Do
                    End If
                    currBufferLine = (currBufferLine + 1) Mod linesToBuffer
                Loop
                sw.Close()
            End Using
        Catch ex As Exception

        End Try
rproffitt commented: Now throw this a zero byte file. Excellent examples where something simple grows and grows to cover every condition. +0
xrjf 230 Posting Whiz

Consider reading all the lines at the beginning and, then, prepending the line number, like in:

        Try
            Dim vLines() As String = IO.File.ReadAllLines("Append.txt")
            Using sw As New StreamWriter("Append.txt")
                For i As Int32 = 0 To vLines.Length - 1
                    sw.Write(String.Format("Line #{0:0000} ", i) + vLines(i) + vbCrLf)
                Next
            End Using
        Catch ex As Exception

        End Try
rproffitt commented: I'd like to try that on a 4+ terabyte file just to see what vb.net would do. There are reasons to code this with input and output files. +15
xrjf 230 Posting Whiz

Be sure to have all the tags 'closed' (e.g. <asp:Panel ... /> or <asp:Panel .... > ....</asp:Panel>) and all enclosed inside <form>...</form>.
For example:

<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID = "LblDate" runat="server" CssClass="dateStyle" Text="Label"></asp:Label>
            <asp:Panel ID="pnlFormFields" runat="server" /> 
            <asp:Panel ID="pnlThankYouMessage" runat="server" CssClass="panel" Visible="False">
                    Thank you. Your message has been sent.
            </asp:Panel>
        </div>
    </form>
</body>
xrjf 230 Posting Whiz

Unexpectedly for me, when datasource is assigned, dessing mode seems to be bypassed. Commenting the If condition columns and rows can added to the datatable, directly to the control in dessing time or dynamically at run-time.

Public Class ClsDgvJournal
    Inherits DataGridView
    Public dataTbl As New DataTable
    Public Sub New()
        Try
            Width = 555
            Height = 90
            'If System.ComponentModel.LicenseManager.UsageMode = System.ComponentModel.LicenseUsageMode.Designtime Then'
            Dim dc1 As New DataColumn("AAA", GetType(String))
            Dim dc2 As New DataColumn("BBB", GetType(Int32))
            Dim dc3 As New DataColumn("CCC", GetType(Int32))
            Dim dc4 As New DataColumn("DDD", GetType(Int32))
            Dim dc5 As New DataColumn("EEE", GetType(Int32))
            dataTbl.Columns.AddRange(New DataColumn() {dc1, dc2, dc3, dc4, dc5})
            Dim row As DataRow = dataTbl.NewRow
            row.ItemArray = New Object() {1, 2, 3, 4, 5}
            dataTbl.Rows.Add(row)
            Me.DataSource = dataTbl
            'End If'
        Catch ex As Exception

        End Try
    End Sub

End Class

Public Class Form1

    Dim nItem As Int32 = 6
    Private Sub btnAddRow_Click(sender As Object, e As EventArgs) Handles btnAddRow.Click
        Try
            With ClsDgvJournal1.dataTbl
                Dim row As DataRow = .NewRow
                row.ItemArray = New Object() {nItem, nItem + 1, nItem + 2, nItem + 3, nItem + 4}
                .Rows.Add(row)
            End With
            nItem += 5
        Catch ex As Exception

        End Try
    End Sub
End Class
xrjf 230 Posting Whiz

Still the code was throwing exceptions until the function shifted to a shared function and the code was as below. Now it works smoothly.

    Shared Function SearchComPort(obj As sComObj) As Boolean
        Try
            obj.sCom = ""
            Dim sCom As String
            Dim info As Management.ManagementObject
            Dim searcher As New System.Management.ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity where deviceID like '%usb%'")
            For Each info In searcher.Get()
                Dim deviceID As String = info("deviceID").ToString
                If InStr(LCase(deviceID), LCase("vid_" + obj.VID + "&pid_" + obj.PID)) Then
                    sCom = CType(info("name"), String)
                    Dim pos As Int32 = InStrRev(sCom, "(")
                    sCom = Mid(sCom, pos + 1)
                    sCom = Mid(sCom, 1, Len(sCom) - 1)
                    obj.sCom = sCom
                    Return True
                End If
            Next
        Catch ex As Exception

        End Try
        Return False
    End Function
xrjf 230 Posting Whiz

I continue this thread because actually I've re-written some C# code, that communicates with a usb device, in Visual Basic.
The thing is that when trying to find the COM port to which the device is connected at, the code was throwing an InvalidCastException. After searching a while the internet the solution is not to call the function directly, but through a thread:

    Function FindDeviceAndOpen() As Boolean
        Try
            If Not IsOpen Then
                If sCom = "" Then
                    Dim o As New sComObj
                    Dim t As New System.Threading.Thread(AddressOf SearchComPort)
                    t.Start(o)
                    t.Join()
                    sCom = o.sCom
                End If
            End If
            If sCom IsNot Nothing AndAlso sCom.Length Then
                Open()
            End If
        Catch ex As Exception

        End Try
    End Function
    Class sComObj
        Public sCom As String
    End Class
    Sub SearchComPort(obj As sComObj)
        Try
            Dim info As Management.ManagementObject
            Dim searcher As System.Management.ManagementObjectSearcher _
                    = New System.Management.ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity WHERE DeviceID Like '%vid_" + VID + "&pid_" + PID + "%'")
            For Each info In searcher.Get()
                sCom = CType(info("name"), String)
                Dim pos As Int32 = InStrRev(sCom, "(")
                sCom = Mid(sCom, pos + 1)
                obj.sCom = Mid(sCom, 1, Len(sCom) - 1)
                info.Dispose()
                searcher.Dispose()
                Exit For
            Next
        Catch ex As Exception

        End Try
    End Sub
xrjf 230 Posting Whiz

I adjoint the project once again because I found it was throwing errors, did you find any? If you find any further error please let me know.

IP_Textbox3.PNG

xrjf 230 Posting Whiz

To get error line number I would enclose inside a try-catch.

xrjf 230 Posting Whiz

I am very happy that you could resolve the issue. Thanks.

xrjf 230 Posting Whiz

There should be no problem by name. Could you upload an image of the Console listing the name (option 2.) ? Use the snipping tool for that purpose.

rproffitt commented: I agree but I've seen folk go down this rabbit hole and the name wasn't in the data. +15
xrjf 230 Posting Whiz

¿Are you entering the complete name? The select command is NOT case sensitive, but if you want to use the percent wildcard '%', the function would be then:

    Function Find_Device_By_Name(name As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager. '
            Dim info As Management.ManagementObject
            Dim search As New System.Management.ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%" + name + "%'")
            For Each info In search.Get()
                Dim devname As String = CType(info("Name"), String)
                Dim ID As String = CType(info("DeviceID"), String)
                Console.WriteLine("Device ID is: " + ID.ToString)
                Console.WriteLine("       name=" + devname)
            Next
            Return True ' Device(s) Found '
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for '
        Return False
    End Function
xrjf 230 Posting Whiz

BTW you may cast from one type to another by means of DirectCast() or CType().

xrjf 230 Posting Whiz

Vendor ID (VID) and Product (ID) is not the same as serial number. Two equal devices from the same vendor will have the same VID & PID because are the same product from the same vendor, but different serial numbers.
I have made same changes to the code so you can find also a device by name:

Imports System.Management

Module Module1

    Dim vIDs() As String, iv As Int32 = 0
    Dim deviceID = "VID_0461&PID_4E22" ' Change to your's 
    Dim bDsp As Boolean = True
    Dim bAttached As Boolean = False
    Sub Main()
        Do
            Console.WriteLine("1. List All Devices")
            Console.WriteLine("2. List USB Devices")
            Console.WriteLine("3. Find out the device ID")
            Console.WriteLine("4. Find if Device " + deviceID + " is connected.")
            Console.WriteLine("5. Find device(s) by name.")
            Console.WriteLine("6. Exit")
            Select Case Console.ReadLine
                Case "1" : Detect_missing_VID_PID()
                Case "2" : Detect_missing_VID_PID("USB" + Chr(92))
                Case "3"
                    Console.Clear()
                    Console.WriteLine("Press 'Enter' key when the device is attached.")
                    Console.ReadLine()
                    bDsp = False
                    iv = 0
                    Detect_missing_VID_PID("USB" + Chr(92))
                    Console.WriteLine("Detach the device and press 'Enter' key.")
                    Console.ReadLine()
                    Detect_missing_VID_PID("USB" + Chr(92))
                    Console.WriteLine("Device ID is: " + deviceID)
                    Console.WriteLine("Attach again the device and press 'Enter' key.")
                    Console.ReadLine()
                    bAttached = Find_Device_By_ID(deviceID)
                    Console.WriteLine("Now on if you attach/remove it'll be detected. Press any key to exit.")
                    Do
                        Dim nowAttached As Boolean = Find_Device_By_ID(deviceID)
                        If nowAttached <> bAttached Then
                            bAttached = nowAttached
                            If bAttached Then
                                Console.WriteLine("Attached")
                            Else
                                Console.WriteLine("Removed")
                            End If
                        End If
                        System.Threading.Thread.Sleep(500)
                    Loop While Not Console.KeyAvailable
                    bDsp = True
                Case "4"
                    If Find_Device_By_ID(deviceID) Then
                        Console.WriteLine("Connected!")
                    End If
                Case "5"
                    Console.Write("Device's name is?: ")
                    Dim …
xrjf 230 Posting Whiz

I imagine you'll want to know if the mouse is attached or removed. Here is another version where this task is done (in option 3).

Imports System.Management

Module Module1

    Dim vIDs() As String, iv As Int32 = 0
    Dim VID_PID_device = "VID_0461&PID_4E22" ' Change to your's 
    Dim bDsp As Boolean = True
    Dim bAttached As Boolean = False
    Sub Main()
        Do
            Console.WriteLine("1. List All Devices")
            Console.WriteLine("2. List USB Devices")
            Console.WriteLine("3. Find out the VID and the PID of the mouse.")
            Console.WriteLine("4. Find if Device " + VID_PID_device + " is connected.")
            Console.WriteLine("5. Exit")
            Select Case Console.ReadLine
                Case "1" : ListDevices_VID_PID()
                Case "2" : ListDevices_VID_PID("USB" + Chr(92))
                Case "3"
                    Console.Clear()
                    Console.WriteLine("Press 'Enter' key when the mouse is attached.")
                    Console.ReadLine()
                    bDsp = False
                    iv = 0
                    ListDevices_VID_PID("USB" + Chr(92))
                    Console.WriteLine("Detach the mouse and press 'Enter' key.")
                    Console.ReadLine()
                    ListDevices_VID_PID("USB" + Chr(92))
                    Console.WriteLine("Mouse VID and PID is: " + VID_PID_device)
                    Console.WriteLine("Attach again the mouse and press 'Enter' key.")
                    Console.ReadLine()
                    bAttached = Find_Device_By_VID_PID(VID_PID_device)
                    Console.WriteLine("Now on if you attach/remove it'll be detected. Press any key to exit.")
                    Do
                        Dim nowAttached As Boolean = Find_Device_By_VID_PID(VID_PID_device)
                        If nowAttached <> bAttached Then
                            bAttached = nowAttached
                            If bAttached Then
                                Console.WriteLine("Attached")
                            Else
                                Console.WriteLine("Removed")
                            End If
                        End If
                        System.Threading.Thread.Sleep(500)
                    Loop While Not Console.KeyAvailable
                    bDsp = True
                Case "4"
                    If Find_Device_By_VID_PID(VID_PID_device) Then
                        Console.WriteLine("Connected!")
                    End If
                Case "5" : Exit Do
            End Select
        Loop
    End Sub
    Sub ListDevices_VID_PID(Optional sFilter As String = "")
        Try
            Dim bCompare As Boolean = IIf(iv = 0, False, True)
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name …
xrjf 230 Posting Whiz

As you may know, each device has a unique Vendor Identifier (VID) and a Product Identifier (PID). If, for example, I want to know if the mouse is connected, what shall I do? I can list all the devices with their VID and PID. Then unplug the mouse, list again all the devices and compare with the former list and see which device is missing: the missing device will tell me the mouse's VID and PID.
Once I know the VID and PID, it will be possible to detect if the mouse is connected or not.

Imports System.Management

Module Module1

    Sub Main()
        Dim VID_PID_device = "VID_0461&PID_4E22" ' Change to your's 
        Console.WriteLine("1. List All Devices")
        Console.WriteLine("2. List USB Devices")
        Console.WriteLine("3. Find if Device " + VID_PID_device + " is connected.")
        Select Case Console.ReadLine
            Case "1" : ListDevices_VID_PID()
            Case "2" : ListDevices_VID_PID("USB"+Chr(92))
            Case "3" 
                If Find_Device_By_VID_PID(VID_PID_device) Then
                    Console.WriteLine("Connected!")
                End If
        End Select
        Console.Write("Press Enter Key to exit.")
        Console.ReadLine()
    End Sub
    Sub ListDevices_VID_PID(Optional sFilter As String = "")
        Try
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                Name = CType(info("Caption"), String)
                Dim ID As String = CType(info("DeviceID"), String)
                If sFilter = "" OrElse InStr(ID, sFilter) Then
                    Console.WriteLine(Name + " " + ID)
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub
    Function Find_Device_By_VID_PID(Device_VID_PID As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager. '
            Dim info As …
xrjf 230 Posting Whiz

You should know by now or take a programming course: call the function passing the name of the device as argument.

xrjf 230 Posting Whiz

In Visual Studio go to the Solution Explorer and right click over "References". It will look something like this:

ListDevices0.PNG

A dialog window will be opened. Select "Framework" on the left pane, and click the check box for System.Management.

ListDevices.PNG

Accept and the error should disappear.

xrjf 230 Posting Whiz

If you want to list only USB devices, you may do:

    Function DetectDevice(DeviceName As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager.'
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.'
                Name = CType(info("Caption"), String) ' Get the name of the device.'
                Dim ID As String = CType(info("DeviceID"), String)
                If InStr(info.Path.ToString, "USB\\") Then
                    Console.WriteLine(Name + " " + ID)
                    If InStr(Name, DeviceName, CompareMethod.Text) > 0 Then
                        Return True
                    End If
                End If
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for'
        Return False
    End Function
xrjf 230 Posting Whiz

Click Here
You should add a reference to System.Management dll

    Function DetectDevice(DeviceName As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager.'
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.'
                Name = CType(info("Caption"), String) ' Get the name of the device.'
                If InStr(Name, DeviceName, CompareMethod.Text) > 0 Then
                    Return True
                End If
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for'
        Return False
    End Function
xrjf 230 Posting Whiz

You must add a condition because the columns are being added twice: in design-time and in run time. (DesignMode property from Windows Forms components not 100% reliable, so use this other):

    Public Sub New()
        Width = 500
        Height = 200
        If System.ComponentModel.LicenseManager.UsageMode = System.ComponentModel.LicenseUsageMode.Designtime Then
            Dim Col1 = New DataGridViewTextBoxColumn With {.HeaderText = "AAA", .Name = "A", .Width = 100}
            Dim Col2 = New DataGridViewTextBoxColumn With {.HeaderText = "BBB", .Name = "B", .Width = 200}
            Dim Col3 = New DataGridViewTextBoxColumn With {.HeaderText = "CCC", .Name = "C", .Width = 100}
            Dim Col4 = New DataGridViewTextBoxColumn With {.HeaderText = "DDD", .Name = "D", .Width = 100}
            Dim Col5 = New DataGridViewTextBoxColumn With {.HeaderText = "EEE", .Name = "E", .Width = 100}
            Me.Columns.AddRange({Col1, Col2, Col3, Col4, Col5})
        End If

    End Sub
xrjf 230 Posting Whiz

The EXE, running by itself as you say, is working with no problem for me.

    Private Sub cmdCreate_File_Click(sender As Object, e As EventArgs) Handles cmdCreate_File.Click
        Dim InFolder As String = txtFolderToBrowse.Text
        Dim sInFile As String
        Dim sTitle As String
        Dim sArtist As String
        Dim MyData As MediaID3Structure
        Dim sOutput As String
        Dim sCurrentPath As String
        Dim filePath As String
        Dim fileName As String
        Dim swFile As StreamWriter

        Try
            If txtFolderToBrowse.Text = "" Then
                MsgBox("You haven't selected a folder that has MP3 files")
                txtFolderToBrowse.Focus()
                Exit Sub
            End If

            If Microsoft.VisualBasic.Left(InFolder, 1) <> "\" Then
                InFolder = InFolder & "\"
            End If

            sCurrentPath = Application.StartupPath & "\SongFilesForUpload\"

            fileName = "MusicFiles_" & Format(Now(), "yyyyMMdd_hhmmss") & ".csv"

            filePath = Path.Combine(sCurrentPath, fileName)

            Dim OutFile As String = filePath

            swFile = New System.IO.StreamWriter(OutFile)
            sOutput = "Titile,Artist"
            swFile.WriteLine(sOutput)

            For Each i As String In Directory.GetFiles(InFolder, "*.mp3")
                Try
                    sInFile = Path.GetFileName(i)    'Get name of file so that you can get the information

                    MyData = GetMediaData(InFolder & sInFile)

                    sTitle = Replace(Replace(Replace(MyData.Title, ",", ",,"), "&", "&&"), "+", "++")
                    sArtist = Replace(Replace(Replace(MyData.Artist, ",", ",,"), "&", "&&"), "+", "++")

                    sOutput = sTitle & "," & sArtist
                    swFile.WriteLine(sOutput)
                Catch ex As Exception
                    MsgBox("You Received the following error:  " & ex.Message)
                End Try
            Next
            swFile.Close()
            MsgBox("File has been created.  Open folder to review")
        Catch ex As Exception
            MsgBox("You Received the following error:  " & ex.Message)
        End Try
    End Sub
    Public Structure MediaID3Structure
        Dim Artist As String
        Dim Album As String
        Dim Title As String
        Dim Genre As String
        Dim Year As String
    End …
xrjf 230 Posting Whiz

Just split the fields inside each row:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            For Each row As String In File.ReadAllLines("Table.csv")
                ' split the fields from the row '
                Dim vFields() As String = Split(row, ";")
                If vFields(0).Contains(TextBox1.Text) Then ' vFields(0) = specificaion '
                    lblValue1.Text = vFields(1) ' vFields(1) is value 1 '
                    lblValue2.Text = vFields(2) ' vFields(2) is value 2
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub

TableCSV.PNG

xrjf 230 Posting Whiz

I've made several improvents to the code, so here is another version.

xrjf 230 Posting Whiz

You may want to add a user control, with 4 or 6 textboxes depending on IPv4 or IPv6. For example:

Public Class IP_Textbox
    Const nBytes As Int32 = 4 ' IPv4 (change to =6 if IPv6)
    Dim vTextbox(nBytes - 1) As TextBox
    Dim vLabel(nBytes - 2) As Label
    Private Sub IP_Textbox_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Me.BackColor = Color.White
            Dim left As Int32 = 4
            For i As Int32 = 0 To nBytes - 1
                vTextbox(i) = New TextBox
                With vTextbox(i)
                    .Width = 25
                    .TextAlign = HorizontalAlignment.Center
                    .BorderStyle = BorderStyle.None
                    .BackColor = Color.White
                    .MaxLength = 3
                    .Location =
                        New Point(left, 3 + (Me.Height - vTextbox(i).Height) / 2)
                    AddHandler .Validating, AddressOf vTextChanged
                    left += 25
                End With
                Me.Controls.Add(vTextbox(i))
                If i < nBytes - 1 Then
                    vLabel(i) = New Label
                    With vLabel(i)
                        .AutoSize = True
                        .Text = ","
                        .BorderStyle = BorderStyle.None
                        .BackColor = Color.White
                        .Location = New Point(left, 7)
                        left += 10
                    End With
                    Me.Controls.Add(vLabel(i))
                End If
            Next
            Me.Width = left + 6
            Me.Height += 2
        Catch ex As Exception

        End Try
    End Sub
    Public ReadOnly Property IP As String()
        Get
            Dim vText(vTextbox.Length - 1) As String
            Try
                For i As Int32 = 0 To vText.Length - 1
                    vText(i) = vTextbox(i).Text
                Next
            Catch ex As Exception

            End Try
            Return vText
        End Get
    End Property
    Private Sub vTextChanged(sender As Object, e As System.ComponentModel.CancelEventArgs)
        Try
            Dim tb As TextBox = CType(sender, TextBox)
            tb.Text = Trim(tb.Text)
            If Len(tb.Text) = 0 Then tb.Text = "0"
            Dim ip As Int32
            If Int32.TryParse(tb.Text, ip) AndAlso …
xrjf 230 Posting Whiz

Coding like the following you get the attached image:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListView1.View = View.Details
        For i As Int32 = 0 To 3
            Dim ch As ColumnHeader = ListView1.Columns.Add("Column " + (i + 1).ToString)
            ch.Width = 100
        Next

        With ListView1
            Dim vDates() As String = {"2019/01/01", "2019/01/01", "2019/01/01", "2019/01/02", "2019/01/02"}
            Dim lastID As Int32 = -1
            For id = 1 To 5
                Dim lastD As String = ""
                For Each d In vDates
                    Dim vFields() As String = {
                    " field A",
                    " field B"
                        }
                    Dim li As ListViewItem
                    If id <> lastID Then
                        li = .Items.Add(id.ToString)
                        lastID = id
                    Else
                        li = .Items.Add("")
                    End If
                    If d <> lastD Then
                        li.SubItems.Add(d)
                        lastD = d
                    Else
                        li.SubItems.Add("")
                    End If
                    For iRow As Int32 = 0 To vFields.Length - 1
                        Dim str As String = "ID:" + id.ToString + " date:" + d
                        li.SubItems.Add(str + vFields(iRow))
                    Next
                Next
            Next
        End With
    End Sub
End Class

ListView.PNG

xrjf 230 Posting Whiz

Forget all what I said. You just have to add two lines to Module1 in Function copy_template(Newsht As String):

Sheets(Newsht).Cells(44, 20) = 0
Sheets(Newsht).Cells(45, 20) = 0

So the function now will be:

Function copy_template(Newsht As String)
 Dim MyDate
MyDate = Sheets("PROJECT_INFORMATION").Range("G2")
    ShowSheets
    Worksheets("wbs_template").Visible = True
    Sheets("wbs_template").Select
    Sheets("wbs_template").Copy before:=Sheets("Rates")
    Worksheets("wbs_template").Visible = False
    Sheets("wbs_template (2)").Select
    Sheets("wbs_template (2)").Name = Newsht
    Sheets(Newsht).Activate
    Sheets(Newsht).Cells(23, 6) = "1"
    Range("E8").Value = Sheets("PROJECT_INFORMATION").Range("A2")
    Range("G8").Value = MyDate
    Range("N8").Value = Newsht
    Range("N8").Select
    Range("I8").Value = Sheets("PROJECT_INFORMATION").Range("D2")
    Range("A1").Select
    Sheets(Newsht).Cells(23, 6) = "0"
    Sheets(Newsht).Cells(44, 20) = 0
    Sheets(Newsht).Cells(45, 20) = 0
    applydata
    HideSheets
End Function
xrjf 230 Posting Whiz

As far as I've reached (Sub Add_SP_Rec(WBSNum As String) changing the lines order (first format, then formula):

    Worksheets("SUMMARY").Cells(lastRow, 1).Select
    Selection.NumberFormat = "00.000"
    Selection.Formula = WBSITEMNUMBER
    WBSITEMNUMBER = "=IF('" & WBSNum & "'!T$44<>0,'" & WBSNum & "'!N$8,"""")"

solves first error. Next change it's name to the function below or to variable lastRow, because variable lastRow is losing its value.

Function lastRow(shtname As Worksheet)
    Dim sh As Worksheet
    On Error Resume Next
    Set sh = Sheets(shtname)
    lastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

Also, for some reason cell's text is #N/A, so the next line of code throws an error:

iSheetString = iSheet.Cells(lastRow, 1).Value
xrjf 230 Posting Whiz

Why not launch a modal pop-up from client side or server side using Ajax Toolkit? See Here

xrjf 230 Posting Whiz

I can't reply to you as it is meant because the Excel Sheet you send is missing, for example, "WBS_Items" or "tableinfo" and so on. In this manner is impossible to know what the data is and what you're trying to do. If you please, you may complete all the information.

xrjf 230 Posting Whiz

I haven't tried your code, but instead of using wsSource.Cells(Rows.Count, 1).End(xlUp).Row, you could use .UsedRange. UsedRange knows really where the data ends.

xrjf 230 Posting Whiz

Looks like there is a comparison between a numeric value (PROPID) and a string ('%" & Textbox2.Text & "%' ). The solution is to convert both to same type by means of CAST or CONVERT:
Syntax for CAST:
CAST ( expression AS data_type [ (length ) ])
or
Syntax for CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

xrjf 230 Posting Whiz

Assuming you correct the XML file and you know the name of the fields, you could do something like the following:

Imports System.IO

Public Class XMLreader
    Private Sub Populate_Click(sender As Object, e As EventArgs) Handles Populate.Click
        extractFields()
    End Sub
    Sub extractFields()
        Try
            Dim svFields() As String = {"code", "codeSystemName"}
            Dim vFieldType() As Type = {GetType(Int32), GetType(String)}
            Dim dt As New DataTable
            For i As Int32 = 0 To svFields.Length - 1
                dt.Columns.Add(New DataColumn(svFields(i), vFieldType(i)))
            Next
            Dim _assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly
            Dim sr As Stream = _assembly.GetManifestResourceStream("XMLreader.XMLreader.xml")
            Using xtr As System.Xml.XmlReader = System.Xml.XmlReader.Create(sr)
                Do While xtr.Read
                    If xtr.IsStartElement Then
                        If xtr.HasAttributes Then
                            Dim nFields As Int32 = 0
                            Dim vRow(svFields.Length - 1)
                            While xtr.MoveToNextAttribute
                                Dim pos As Int32 = Array.IndexOf(svFields, xtr.Name)
                                If pos > -1 Then
                                    vRow(pos) = xtr.Value
                                    nFields += 1
                                    If nFields = svFields.Length Then
                                        Dim dr As DataRow = dt.NewRow
                                        dr.ItemArray = vRow
                                        dt.Rows.Add(dr)
                                    End If
                                End If
                            End While
                        End If
                    End If
                Loop
            End Using
            With DataGridView1
                .DataSource = dt
                .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells)
            End With
        Catch ex As Exception

        End Try
    End Sub
End Class
xrjf 230 Posting Whiz

What do you mean by a "slow" machine? Anyway verify the path of the images. If the images are not found there will not be no message unless you add a line after line number 95, for example `If i = -1 AndAlso not IO.File.Exists(path) Then msgbox("file not found: "+path)

xrjf 230 Posting Whiz

Or you can change current's thread date pattern:

                Dim newCulture As System.Globalization.CultureInfo =
                    System.Threading.Thread.CurrentThread.CurrentCulture.Clone()
                newCulture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"
                newCulture.DateTimeFormat.DateSeparator = "-"
                System.Threading.Thread.CurrentThread.CurrentCulture = newCulture
                Dim sDate As String = Now.ToString
xrjf 230 Posting Whiz

Take a look here

                Dim dt As DateTime = Now
                Dim sDate As String = dt.ToString("yyyy-MM-dd")
xrjf 230 Posting Whiz

It has to do with the algorithm. The usual method for parsing mathematical expressions is the shunting yard algorithm. You may consider reading it's description here.

xrjf 230 Posting Whiz

The code is throwing no error. Seems as if you haven't compiled the new code. You should execute "javac" from the command prompt, have you?

xrjf 230 Posting Whiz

You are right @JamesCherill, that's the same feeling I'm getting: copy and paste.

xrjf 230 Posting Whiz

If you set the code as I send it to you, you won't have that problem with none of those examples.

xrjf 230 Posting Whiz

You just have to proceed similarly as for the "+" and "-" operators. Now, the code is:

import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.Integer.*;
import static java.lang.System.*;

public class ExpressionSolver
{
    int answer;
    String expString;
    ArrayList<String> exp;
    public ExpressionSolver(String s)
    {
        setExpression(s);
    }

    public void setExpression(String s)
    {
        expString = s;
        exp = new ArrayList<String>();

        for(String temp: s.split(" "))
        {
         exp.add(temp);
        }
    }

    public void solveExpression()
    { 
       int index1, index2, num1, num2;        

      while(exp.contains("*") || exp.contains("/"))
      {
           index1 = exp.indexOf("*");
           index2 = 0;
           if(index1 <= 0)
           {
             index1 = exp.indexOf("/");
             index2 = 1;
           }
         num1 = Integer.parseInt(exp.get(index1-1));
         num2 = Integer.parseInt(exp.get(index1+1));
        if(index2 == 0)
         {
            answer = num1 * num2;
         }
         else
         {
            answer = num1 / num2;
         }
         exp.remove(index1 - 1);
         exp.remove(index1 - 1);
         exp.set(index1 - 1, Integer.toString(answer));
      }
      while(exp.contains("+") || exp.contains("-"))
      {
           index1 = exp.indexOf("+");
        index2 = 0;
           if(index1 <= 0)
           {
             index1 = exp.indexOf("-");
          index2 = 1;
           }
         num1 = Integer.parseInt(exp.get(index1-1));
         num2 = Integer.parseInt(exp.get(index1+1));
        if(index2 == 0)
         {
            answer = num1 + num2;
         }
         else
         {
            answer = num1 - num2;
         }

         exp.remove(index1 - 1);
         exp.remove(index1 - 1);
         exp.set(index1 - 1, Integer.toString(answer));

      }
}

  public String toString()   
  {
   return expString + " = " + answer;
  }
}
xrjf 230 Posting Whiz

I've only take a look to addition and substraction and made some modifications. I hope you understand it and leave up to you the other operators.

import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.Integer.*;
import static java.lang.System.*;

public class ExpressionSolver
{
    int answer;
    String expString;
    ArrayList<String> exp;
    public ExpressionSolver(String s)
    {
        setExpression(s);
    }

    public void setExpression(String s)
    {
        expString = s;
        exp = new ArrayList<String>();

        for(String temp: s.split(" "))
        {
         exp.add(temp);
        }
    }

    public void solveExpression()
    { 
       int index1, index2, num1, num2;        

       while(exp.contains("*") || exp.contains("/"))
       {
         index1 = exp.indexOf("*");
         index2 = exp.indexOf("/");

         if(index1 <= 0)
         {
          index1 = 100;
         }
         if (index2 <= 0)
         {
          index2 = 100;
         }

          if(index1 < index2)
         {   
          num1 = Integer.parseInt(exp.get(index1-1));
          num2 = Integer.parseInt(exp.get(index1+1));
          answer = num1 * num2;

          exp.remove(index1 - 1);
          exp.remove(index1 - 1);
          exp.set(index1 - 1, Integer.toString(answer));
         }
         else if(index2 < index1)
         {
           num1 = Integer.parseInt(exp.get(index2 - 1));
           num2 = Integer.parseInt(exp.get(index2 + 1));
           answer = num1 / num2;

           exp.remove(index2 -1);
           exp.remove(index2 - 1);
           exp.set(index1 -1 ,Integer.toString(answer));
          }
      }
      while(exp.contains("+") || exp.contains("-"))
      {
           index1 = exp.indexOf("+");
        index2 = 0;
           if(index1 <= 0)
           {
             index1 = exp.indexOf("-");
          index2 = 1;
           }
         num1 = Integer.parseInt(exp.get(index1-1));
         num2 = Integer.parseInt(exp.get(index1+1));
        if(index2 == 0)
         {
            answer = num1 + num2;
         }
         else
         {
            answer = num1 - num2;
         }

         exp.remove(index1 - 1);
         exp.remove(index1 - 1);
         exp.set(index1 - 1, Integer.toString(answer));

      }
}

  public String toString()   
  {
   return expString + " = " + answer;
  }
}
xrjf 230 Posting Whiz

Of course if you're not coding in VBasic like me, most probably you'll have to escape the slash /. So the pattern becomes collections\/(?!\/|shirts|tea|[\w]+\/products)

xrjf 230 Posting Whiz

Assuming products (if present) is after the second / character like in
collections/shirts/products/tee-shirt,
collections(/(?!/|shirts|tea|[\w]+/products)) seems to work.

EvolutionFallen commented: Perfect! Just what I was looking for. +9