Saturday, November 5, 2011

How to Read the Contents of the Directory in Visual Basic .Net


In Visual Basic 6, it is awkward to read the contents of a directory: you have to call the Dir$ function repeatedly. This function returns the name of the first file in the directory, and then the next, and so on. You cant examine two directories at the same time because Dir$ tracks only the file it has enumerated for the current directory. In Visual Basic .NET, getting the list of files in a directory is much simpler. Use the System.IO.Directory.GetFiles method to return an array of filenames. The following sample code is from the Dashboard.GetSubForms method in the DynamicApp project:
Dim filePathArray() As String
filePathArray = System.IO.Directory.GetFiles(myDirectory(), "*.dll")
After this code runs, the filePathArray variable is filled with an array of file paths, such as
C:DynamicShellbinGraphicsFeatures.dll
The System.IO namespace contains many other useful functions as well. For example, System.IO.Path.GetDirectoryName returns the directory name from a file path. The code
MsgBox(System.IO.Path.GetDirectoryName( _
   "C:DynamicShellbinGraphicsFeatures.dll"))
shows C:DynamicShell in the message box. In a similar vein, the System.IO.Path.GetFileName methodreturns the filename of a file path. For example, the code
MsgBox(System.IO.Path.GetFileName( _
  "C:DynamicShellbinGraphicsFeatures.dll"))
shows GraphicsFeatures.dll in the message box. Another useful function is System.Reflection.Assembly.GetExecutingAssembly. This last method returns the file path of theapplication. DynamicApp passes the file path to System.IO.Path.GetDirectoryName to get the applications directory, which is how it knows where to look for DLLs.

Read and Write Text File in Visual Basic .Net


While were on the subject of the new file functions, lets take a short digression and quickly discuss how to write to and read from files using the new .NET Framework methods. You can still use the existing Visual Basic file functions, but the .NET Framework file methods, although a little more complicated, offer more flexibility when working with files.
Well create a simple console application that creates a file, writes Hello World to it, closes the file, and then reopens it and shows the contents in a message box.
Sub Main()
   '* Create a file and write to it
   Dim outFile As System.IO.FileStream
   outFile = New System.IO.FileStream("C:tempFile.txt", _
      IO.FileMode.Create, IO.FileAccess.Write)
   Dim fileWriter As New System.IO.StreamWriter(outFile)
   fileWriter.WriteLine("Hello World")
   fileWriter.Close()
   outFile.Close()

   '* Open a file and read from it
   Dim inFile As System.IO.FileStream
   inFile = New System.IO.FileStream("C:tempFile.txt", _
      IO.FileMode.Open, IO.FileAccess.Read)
   Dim fileReader As New System.IO.StreamReader(inFile)
   While fileReader.Peek > -1
      MsgBox(fileReader.ReadLine)
   End While
   fileReader.Close()
   inFile.Close()
 End Sub

To open a file for writing, you have to perform two steps: create a stream object and then create a StreamWriter object to write to the stream. You can then write to the file using the StreamWriter objects Write and WriteLine methods. Reading from a file involves a similar process: create a stream object, and then create a StreamReader to read from the stream. To determine whether there is anything to read from the file, use the StreamReader objects Peek method, which returns the value of the next byte in the file, or 1 if there is nothing left to read. The StreamReader objects Read, ReadBlock, ReadLine, and ReadToEndmethods are used to read the contents of the file.

How to use DataView in Visual Basic .Net


A DataView is an object that allows you to create multiple views of your data and that can be used for data binding. The concept is fairly simple, but its importance cannot be overstated. The flexibility it introduces is impressive because a DataView does not actually change the DataTable from which it is generated. Instead, it offers a filtered window to the data. The following code shows how you can use the DataView control to filter rows based on a column value (in this case, the FirstName and LastName columns):
Function TestDataView()
   Dim adapter As New OleDbDataAdapter("Select * From Customers", _
   connStr)
   Dim ds As New DataSet()

   adapter.Fill(ds)

   Dim view1 As DataView = ds.Tables("Customers").DefaultView
   Dim view2 As DataView = ds.Tables("Customers").DefaultView

   view1.RowFilter = "'LastName' Like 'O%'"
   view2.RowFilter = "'FirstName' Like 'E%'"

   Dim i As Integer

   Debug.WriteLine("All LastNames starting with 'O'")
   For i = 0 To view1.Count - 1
      Debug.WriteLine(view1(i)("LastName"))
   Next

   Debug.WriteLine("All FirstNames starting with 'E'")
   For i = 0 To view2.Count - 1
      Debug.WriteLine(view1(i)("FirstName"))
   Next
End Function

Visual Basic .Net – Binding to Windows Forms Controls


The .NET Framework brings a wide variety of controls to the developer. The Windows Forms controls are found in the System.Windows.Forms namespace, and the vast majority of them support data binding. In general, data binding to a control is far from challenging. It requires that you use an in-memory data store and can usually accept either a DataTable or a DataSet.
The mechanism is very simple. Take a look at the following example, using a DataTable:
Dim adapter As New OleDbDataAdapter("Select * From Customers", _ connStr)
Dim dt As New DataTable()

' Import the query results into the DataTable
adapter.Fill(dt)

' Bind the DataTable to the DataGrid
DataGrid1.DataSource = dt
The DataSet works in almost exactly the same way:
Dim adapter As New OleDbDataAdapter("Select * From Customers", connStr)
Dim ds As New DataSet()

' Import the query results into the DataSet
adapter.Fill(ds)

' Bind a DataTable from the DataSet to the DataGrid
DataGrid1.DataSource = ds.Tables("Customers")
Notice in this example that instead of passing the entire DataSet to the DataGrid, weve chosen to bind only a single table. This is often necessary with controls for which multiple sets of tables dont make sense. The DataGrid is not one of these controls, however. It is capable of a multitable display (try it) and likes the DataSet just fine.

Visual Basic Function to Convert Numeric to String Format


This visual basic programming function that convert the numeric value into string format. This code can be use in Accounting System or Payroll System in printing checks the amount in word format.

Please copy this function in module area and make a code in form, please check the code below to call this function.

In Form1 please add control Text1.Text, Text2.Text and 1 command button, double the command1 button.

Code like this


 Command1_Click
 'Put the result in Text1.Text
 Text1.Text = NumToString(Text2.Text)  'Note : You may also validate Text2 into numbers only.
 End Sub
 
'Function to Convert the Numeric Value into string format.
 
Public Function NumToString(ByVal nNumber As Currency) As String
Dim bNegative As Boolean
 Dim bHundred As Boolean
If nNumber < 0 Then
 bNegative = True
 End If
nNumber = Abs(Int(nNumber))
If nNumber < 1000 Then     If nNumber  100 > 0 Then
 NumToString = NumToString & _
 NumToString(nNumber  100) & " hundred"
 bHundred = True
 End If
 nNumber = nNumber - ((nNumber  100) * 100)
 Dim bNoFirstDigit As Boolean
 bNoFirstDigit = False
 Select Case nNumber  10
 Case 0
 Select Case nNumber Mod 10
 Case 0
 If Not bHundred Then
 NumToString = NumToString & " zero"
 End If
 Case 1: NumToString = NumToString & " one"
 Case 2: NumToString = NumToString & " two"
 Case 3: NumToString = NumToString & " three"
 Case 4: NumToString = NumToString & " four"
 Case 5: NumToString = NumToString & " five"
 Case 6: NumToString = NumToString & " six"
 Case 7: NumToString = NumToString & " seven"
 Case 8: NumToString = NumToString & " eight"
 Case 9: NumToString = NumToString & " nine"
 End Select
 bNoFirstDigit = True
 Case 1
 Select Case nNumber Mod 10
 Case 0: NumToString = NumToString & " ten"
 Case 1: NumToString = NumToString & " eleven"
 Case 2: NumToString = NumToString & " twelve"
 Case 3: NumToString = NumToString & " thirteen"
 Case 4: NumToString = NumToString & " fourteen"
 Case 5: NumToString = NumToString & " fifteen"
 Case 6: NumToString = NumToString & " sixteen"
 Case 7: NumToString = NumToString & " seventeen"
 Case 8: NumToString = NumToString & " eighteen"
 Case 9: NumToString = NumToString & " nineteen"
 End Select
 bNoFirstDigit = True
 Case 2: NumToString = NumToString & " twenty"
 Case 3: NumToString = NumToString & " thirty"
 Case 4: NumToString = NumToString & " forty"
 Case 5: NumToString = NumToString & " fifty"
 Case 6: NumToString = NumToString & " sixty"
 Case 7: NumToString = NumToString & " seventy"
 Case 8: NumToString = NumToString & " eighty"
 Case 9: NumToString = NumToString & " ninety"
 End Select
 If Not bNoFirstDigit Then
 If nNumber Mod 10 <> 0 Then
 NumToString = NumToString & "-" & _
 Mid(NumToString(nNumber Mod 10), 2)
 End If
 End If
 Else
 Dim nTemp As Currency
 nTemp = 10 ^ 12 'trillion
 Do While nTemp >= 1
 If nNumber >= nTemp Then
 NumToString = NumToString & _
 NumToString(Int(nNumber / nTemp))
 Select Case Int(Log(nTemp) / Log(10) + 0.5)
 Case 12: NumToString = NumToString & " trillion"
 Case 9: NumToString = NumToString & " billion"
 Case 6: NumToString = NumToString & " million"
 Case 3: NumToString = NumToString & " thousand"
 End Select
nNumber = nNumber - (Int(nNumber / nTemp) * nTemp)
 End If
 nTemp = nTemp / 1000
 Loop
 End If
 
If bNegative Then
 NumToString = " negative" & NumToString
 End If

End Function

Public Function DollarToString(ByVal nAmount As Currency) As _
 String

Dim nDollar As Currency
 Dim nCent As Currency

nDollar = Int(nAmount)
 nCent = (Abs(nAmount) * 100) Mod 100

DollarToString = NumToString(nDollar) & " dollar"

If Abs(nDollar) <> 1 Then
 DollarToString = DollarToString & "s"
 End If

DollarToString = DollarToString & " and" & _
 NumToString(nCent) & " cent"

If Abs(nCent) <> 1 Then
 DollarToString = DollarToString & "s"
 End If
 
End Function

How to open a password protected MS Access Database using ADO Object


‘Sample visual basic code on how to open a password protected access database using ADO object
Option Explicit
Dim Conn As New ADODB.Connection, ConStr As
String
Private Sub Btn_OpenDB_Method1()
‘Open the connection
Conn.Open “Provider=Microsoft Jet 4.0 OLE DB Provider;Data Source=” & App.Path & “Data1.mdb” & _
“;Jet ” & “OLEDB:Database Password=123456″

MsgBox “Data File is now opened”
Conn.Close
End Sub
Private Sub Btn_OpenDB_Method2()
ConStr = “Data Source=” & App.Path & “Data1.mdb”
Conn.Provider = “Microsoft Jet 4.0 OLE DB Provider”
Conn.ConnectionString = ConStr
Conn.Properties(“Jet OLEDB:Database Password”) = “123456″
Conn.Open

MsgBox “Data File is now opened”
Conn.Close
End Sub