Monday, May 18, 2009

Easy File Reading and Writing

I recommend putting these in a module or class for repeated use.

Declarations
Imports System.IO
Code
'http://www.freevbcode.com/ShowCode.Asp?ID=4492
Public Function ReadFile(ByVal sFullPath As String, _
Optional ByRef sErrInfo As String = "") As String

Dim sContents As String
Dim oReader As StreamReader

Try
oReader = New StreamReader(sFullPath)
sContents = oReader.ReadToEnd()
oReader.Close()
Return sContents
Catch Ex As Exception
sErrInfo = Ex.Message
End Try

End Function

'http://www.freevbcode.com/ShowCode.Asp?ID=4492
Public Function WriteFile( _
ByVal sFullPath As String, ByVal sContents As String, _
Optional ByRef sErrInfo As String = "") As Boolean

Dim oReader As StreamWriter

Try
oReader = New StreamWriter(sFullPath)
oReader.Write(sContents)
oReader.Close()
Return True
Catch Ex As Exception
sErrInfo = Ex.Message
Return False
End Try

End Function

Thursday, May 14, 2009

Tab Index Made Simple

SetTabIndex recursively collects the controls on the form, sorts them from top to bottom, and sets the tab index. Just add "SetTabIndex(Me)" to your form load event.
'SetTabIndex by Chris Hatcher
'http://vbdotsimple.blogspot.com/
Public Sub SetTabIndex(ByVal oParent As Object)
Dim colChildren As New Collection 'Kids under parent
Dim oChild As Control 'Loop variable for kids
Dim iSort() As Integer 'Sort index for kids
Dim iIndex As Integer 'Loop index for kids

For Each oChild In oParent.Controls 'For each kid...
colChildren.Add(oChild) 'Add it to collection
SetTabIndex(oChild) 'Recurse for grandkids
Next 'Next

SortObjByLoc(colChildren, iSort) 'Sort kids by location

For iIndex = 1 To colChildren.Count 'Assign tab index by sort
colChildren.Item(iSort(iIndex)).TabIndex = iIndex
Next
End Sub

'InsertionSort by David B. Ring
'http://www.devx.com/vb2themax/Tip/19469
'Modified to sort controls from top to bottem, left to right
Private Sub SortObjByLoc(ByVal A As Collection, ByRef P() As Integer)
Dim LP As Long
Dim RP As Long
Dim TMP As Long

Dim lTop As Long
Dim lLeft As Long

Dim L As Long = 1
Dim R As Long = A.Count

ReDim P(R)
For TMP = L To R
P(TMP) = TMP
Next

For RP = L + 1 To R
TMP = P(RP)
lTop = A(TMP).Top
lLeft = A(TMP).Left
For LP = RP To L + 1 Step -1
If lTop < A(P(LP - 1)).Top _
Or lTop = A(P(LP - 1)).Top And lLeft < A(P(LP - 1)).Left Then
P(LP) = P(LP - 1)
Else
Exit For
End If
Next LP
P(LP) = TMP
Next RP
End Sub
Enjoy.