Thursday, December 10, 2015

VB.NET - Search Datagridview and Select Cell

The following function will search for a string in a datagridview and then select the cell with the found string. Continuing to call this function on a button click will cycle through the search moving to the next found string until the end of the grid is reached.


    ''' <summary>
    ''' Looks for the passed in string in the grid starting search in current cell. The search moves down current
    ''' column, then moves to the top of the next one and continues search down. Continues to search until reaching
    ''' the end of the grid or until the string is found. When the search string is found, the cell containing the
    ''' string is selected and searching stops.
    ''' </summary>
    ''' <param name="astrSearchString"></param>
    ''' <remarks></remarks>
    Private Sub FindNextStringInGrid(ByVal astrSearchString As String)

        Dim bolResultFound As Boolean = False 'flag to see if something was found

        Try
            'make sure the grid has records to move through
            If dgvResults.Rows.Count > 0 Then

                'make sure search string is not blank
                If astrSearchString.Trim <> "" Then

                    'get row and column indexes of current cell
                    Dim intColCurrentIndex As Integer = dgvResults.CurrentCell.ColumnIndex
                    Dim intRowCurrentIndex As Integer = dgvResults.CurrentCell.RowIndex

                    'loop through the columns
                    For Each col In dgvResults.Columns

                        'only search columns that contain or are to the right of selected cell
                        If dgvResults.Columns.IndexOf(col) < intColCurrentIndex Then
                            'do not search this column
                        ElseIf dgvResults.Columns.IndexOf(col) = intColCurrentIndex Then

                            'only search from selected cell down
                            For Each row In dgvResults.Rows
                                If dgvResults.Rows.IndexOf(row) > intRowCurrentIndex Then
                                    If row.Cells(dgvResults.Columns.IndexOf(col)).Value.ToString.ToLower.Contains(astrSearchString.Trim.ToLower) Then
                                        'select cell when string is found
                                        dgvResults.CurrentCell = dgvResults.Rows(dgvResults.Rows.IndexOf(row)).Cells(dgvResults.Columns.IndexOf(col))
                                        bolResultFound = True
                                        'if a result was found then no longer need to continue looping through rows
                                        Exit For
                                    End If
                                End If
                            Next

                        ElseIf dgvResults.Columns.IndexOf(col) > intColCurrentIndex Then

                            'search entire column
                            For Each row In dgvResults.Rows
                                If row.Cells(dgvResults.Columns.IndexOf(col)).Value.ToString.ToLower.Contains(astrSearchString.Trim.ToLower) Then
                                    'select cell when string is found
                                    dgvResults.CurrentCell = dgvResults.Rows(dgvResults.Rows.IndexOf(row)).Cells(dgvResults.Columns.IndexOf(col))
                                    bolResultFound = True
                                    'if a result was found then no longer need to continue looping through rows
                                    Exit For
                                End If
                            Next
                        End If

                        'if a result was found then no longer need to continue looping through columns
                        If bolResultFound = True Then
                            Exit For
                        End If
                    Next

                    If bolResultFound = False Then
                        MessageBox.Show("Finished searching end of results.", cAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    End If
                Else
                    MessageBox.Show("Please enter search text.", cAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If
            End If

        Catch ex As Exception
            Throw ex
        End Try
    End Sub


Tuesday, January 13, 2015

VB.NET - Export Excel to PDF

Imports System
Imports System.IO
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel


    ''' <summary>
    ''' converts excel spreadsheet to PDF
    ''' </summary>
    ''' <param name="strXLFile">file path of excel spreadsheet</param>
    ''' <param name="strPDF">file path of where to save the pdf</param>
    ''' <remarks></remarks>
    Public Shared Sub ConvertToPDF(ByVal strXLFile As String, ByVal strPDF As String)

        Dim objExcel As Excel.Application
        Dim objWB As Excel.Workbook

        Try

            'Open Excel and the workbook
            objExcel = New Application
            objExcel.Visible = False
            objWB = objExcel.Workbooks.Open(strXLFile)
            objWB.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, strPDF, , , , , , False)

        Catch ex As Exception
            Throw ex
        Finally
            If objWB IsNot Nothing Then
                objWB.Close()
            End If

            NAR(objWB)

            If objExcel IsNot Nothing Then
                objExcel.Quit() ' Need to leave application open for display.
            End If

            NAR(objExcel)
            GC.Collect()
            GC.WaitForPendingFinalizers()
        End Try

    End Sub


    ''' <summary>
    ''' Used to properly clean up excel or powepoint COM objects.
    ''' </summary>
    ''' <param name="o"></param>
    ''' <remarks></remarks>
    Shared Sub NAR(ByVal o As Object)
        Try
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(o)
        Catch

        Finally
            o = Nothing
        End Try
    End Sub

Friday, January 9, 2015

VB.NET - Regular Expression to get all HREF's out of a String

This function will accept a string and return an arraylist of all the HREF's that were inside:

    ''' <summary>
    ''' Using regular expression to get HREF out of string
    '''
    ''' </summary>
    ''' <param name="inputString"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetHtmlTags(inputString As String) As ArrayList
        Dim m As Match
        Dim HRefPattern As String = "<img[^>]+src\\s*=\\s*['\""]([^'\""]+)['\""][^>]*>"
        Dim arrlist As New ArrayList
        Try
            'Using regular expression retrieve all HREFs from the datacontent string
            m = Regex.Match(inputString, HRefPattern, RegexOptions.IgnoreCase Or RegexOptions.Compiled)
            Do While m.Success
                'check to see if the link already exists in the arraylist before adding it again
                If arrlist.Contains(m.Groups(1).ToString()) = False Then
                    arrlist.Add(m.Groups(1).ToString())
                End If

                m = m.NextMatch()
            Loop

            Return arrlist

        Catch ex As Exception
            Throw ex
        End Try
    End Function



VB.NET - Write Text File Using StreamWriter

Imports System.IO

 Dim strDirectory As String = "C:\temp324\"

        If Directory.Exists(strDirectory) = False Then
            Directory.CreateDirectory(strDirectory)
        End If


        Using objWriter As StreamWriter = New StreamWriter(strDirectory & "\links.txt", False)
            objWriter.Write(txtText.Text)
        End Using