Converting a sentence into CamelCase format in Microsoft VB.NET & ASP.NET
Microsoft VB.NET, ASP.NET and C#.NET lacks the function to allow programmers to convert a string, or even a whole sentence into Camel Case format. Therefore, i have written a microsoft .net functions to do just that. This comes very handy especially in converting a list of names into Camel Case format, or converting a string of addresses and many other applications. You name it. If you do not know what a Camel Case format look like, see the example below:
For instance, we are going to convert the following files into Camel Case format.
Dim Sentence1 As String = "is john smith working in microsoft?"
Dim Sentence2 As String = "michael t. ashby is a GREAT programmer. he is young."
Dim Output1, Output2 As String
Output1 = CCase(Sentence1)
Output2 = CCase(Sentence2)
The converted output will be
Output1 : "Is John Smith Working In Microsoft?"
Output2 : "Michael T. Ashby Is A Great Programmer. He Is Young."
Simply copy and paste the following codes below into your microsoft vb.net, asp.net programming code and you can use it right away.
Public Function CCase(ByVal iString As String) As String
'This function converts a string into "Camel Case" format
Dim oString As String = "" 'initialise output string
Dim iLength As Integer = Len(iString) 'the length of input string
Dim P As Integer = 1 'set pointer to start at character 1
Dim iChar As String 'individual stripped character
Dim UpperFlag As Boolean 'flag to mark upper case is required or not
iString = LCase(iString) 'convert to lower case string
While P <= iLength ' while not end of the string (pointer)
iChar = Mid(iString, P, 1) 'strip each character out of the string one by one
If P = 1 Then 'first character
UpperFlag = True 'change first character to upper case
End If
If iChar = " " Or iChar = "-" Then 'blank field encountered.
UpperFlag = True 'raise the flag to mark the next character as upper case
Else 'non-blank field encountered
If UpperFlag = True Then 'if the flag is raised
iChar = UCase$(iChar) 'change the character to uppercase
UpperFlag = False 'undo raising the flag
End If
End If
oString &= iChar 'reassemble characters back into a string as output
P += 1 'next pointer
End While
Return (oString) 'return the reassembled output string
End Function
VB.NET : Convert A Sentence Into Camel Case Format
Posted by Fluffy | 4:05 AM | ccase, vb.net camel case | 1 comments »VB.NET : Absolute Value (ABS)
Posted by Fluffy | 5:10 AM | Add Project Reference VB.NET, Math.ABS | 0 comments »Applying Absolute Value In VB.NET with ABS
VB.NET allows the conversion of figures (both positive and negative) into absolute figures easily. You can use the Mathematical Function as shown below
Math.ABS
For example, to change a figure value of -34167 into absolute figures, we can apply the codes as follows :
Dim myValue as Integer
myValue = Math.ABS(-34167)
MsgBox(myValue) 'The output now becomes 34167
That illustrates the use of the in-built Math.Abs function in VB.NET
Putting application to sleep for a specified miliseconds in VB.NET
In VB.NET, you can make an application idle ( or sleep ) for a specified miliseconds. For example, in your programming code, you might want to let your program to be idle for 500 miliseconds after executing a certain functions and then execute the next function.
Apply the code below between functions:
System.Threading.Thread.Sleep(500)
Note : The number used is in miliseconds
* 1 sec = 1000ms
VB.NET : Access to SQL Server Compact Edition
Posted by Fluffy | 4:59 AM | SQL Server CE, VB.NET | 0 comments »Accessing SQL Server Compact Edition Database using VB.NET
SQL Server Compact Edition, or simply SQL Server CE, allows a very convenient way of fetching data stored locally as cache. It is usually used in situations where commonly used data are stored locally and accessed directly instead of making queries to fetch the data again and again from the main database server. Accessing data stored locally can be many times faster compared to accessing data stored in the main database located somewhere on the network. Hence, by implementing and taking the full advantage of SQL Server CE, you can make your application runs faster.
Firstly, add the following reference at the top of your module programming code
Imports System.Data.SqlServerCe
Next, add the following as global variables so that you can call them anytime, anywhere in your code.
Friend SQLcommCE As SqlCeCommand 'SQL command
Friend daCE As SqlCeDataAdapter 'SQL adapter
Friend SQLConnCETempDB As SqlCeConnection 'SQL connection linking your local database
Then, add the following codes to establish the database connection to where your application loads when it runs. Data Source points to the path where your SQL Server CE database extension *.sdf is stored, and provides the password (if any) in the codes shown below.
SQLConnCETempDB = New SqlCeConnection("Data Source=C:\TempDB.sdf;Password='123'")
SQLConnCETempDB.Open()
Finally, in the programming code where you want to perform query to the database, you can simply use the codes shown as follows.
Dim SQLStm as String
SQLStm = "DELETE FROM LocalTable WHERE MYTABLE_ID = '123'"
SQLcommCE = New SqlCeCommand(SQLStm, SQLConnCETempDB) 'execute the query
SQLcommCE.ExecuteNonQuery()
That will delete the records with MYTABLE_ID = '123' in your LocalTable.
For INSERT INTO, UPDATE, DELETE or any other NonQuery database access, you can use
.ExecuteNonQuery
If you intend to query the table using the SELECT statement, you have to use the following code instead
.CommandType = CommandType.Text
See the example below:
Dim SQLStm as String
Dim ds as DataSet
Dim Rank, Name as String
SQLStm = "SELECT Rank, Name FROM LocalTable WHERE MYTABLE_ID = '123'"
SQLcommCE = New SqlCeCommand(SQLStm, SQLConnCETempDB) 'SQL query
SQLcommCE.CommandType = CommandType.Text
daCE = New SqlCeDataAdapter(SQLcommCE) 'Retrieve data from SQL Server CE
ds = New DataSet
daCE.Fill(ds) 'Populate dataset with retrieved data.
If ds.Tables(0).Rows.Count > 0 Then ' If record exists in LocalTable
Rank = ds.Tables(0).Rows(0).Item("Rank").ToString
Name = ds.Tables(0).Rows(0).Item("Name").ToString
Else 'record not exists in LocalTable
Rank = ""
Name = ""
End If
Now you can start implementing SQL Server CE in your applications
VB.NET : Mathematical Functions (Advanced)
Posted by Fluffy | 6:24 AM | Advanced Mathematical Functions, VB.NET | 0 comments »Using Advanced Mathematical Functions in VB.NET
More advanced mathematical functions in VB.NET utilizes the System.Math class. This class supports a wide variety of in-built functions such as :
Constants like E and Pi
Trigonometric functions like Sin, Cos & Tan
Logarithmic functions like Log & Log10
and other functions like Ceiling, Floor, Max, Min, Pow, Exp, Sqrt, Abs, Round etc.
The example below shows how some of these advanced mathematical functions are used.
Dim i, j, k as Integer
i = Math.Sqrt(25)
j = Math.Pow(2,5)
k = Math.Abs(-25)
Msgbox(i) '--- result has a value of 5
Msgbox(j) '--- result has a value of 32
Msgbox(k) '--- result has a value of 25
See also Simple Mathematical Functions
VB.NET : Mathematical Functions
Posted by Fluffy | 6:13 AM | Simple Mathematical Functions, VB.NET | 0 comments »Mathematical Functions in VB.NET
VB.NET offers some very simple and useful mathematical functions for your programming needs; They include:
"+" Add
"-" Subtract
"*" Multiply
"/" Divide
"\" Integer Division
"^" Exponent
The code example below illustrates how these mathematical functions are performed in VB.NET.
Dim i, j, k as Integer
i = 2 * 3
j = 3 / 9
k = 2 ^ 3
Msgbox(i) '--- return a value of 6
Msgbox(j) '--- return a value of 3
Msgbox(k) '--- return a value of 8
Now you should have understood the simple mathematical functions in VB.NET.
See also Advanced Mathematical Functions
Microsoft Enterprise Servers
Posted by Fluffy | 5:05 AM | Microsoft Enterprise Servers | 0 comments »Microsoft Enterprise Servers that can be incorporated in system development.
Microsoft SQL Server
Microsoft SQL Server include rich XML functionalites. It also enables the manipulating of XML data by using Transact-SQL (T-SQL). It has supports for Worldwide Web Consortium (W3C) and has a flexible and powerful web-based analysis feature. It provides a safe and secure way of accessing data in the SQL server over the web by using HTTP.
Microsoft BizTalk Server
Microsoft BizTalk Server provices enterprise application integration (EAI), business-to-business integration, and advanced BizTalk Ochestration Technology to build highly customized processes that can be implemented across applications, various platforms, and organizations over the Internet.
Microsoft Host Integration Server
Microsoft Host Integration Server is meant as a replacement for the SNA Server. It provides a solution to embrace the Internet, intranet, and client-server technologies through existing legacy system and infrastructure.
Microsoft Exchange Enterprise Server
Microsoft Exchange Enterprise Server is implemented as a powerful messaging and collaboration technology system with added various important features and provides commendable reliability, scalability and performance of its core infrastructure.
Microsoft Application Center
Microsoft Application Center provides a tool as a way of deploying and managing for the high-availability of Web applications.
Microsoft Internet Security and Acceleration Server
Microsoft Internet Security and Acceleration Server is a feature that provides secure, fast and manageable Internet connectivity. It is built upon Windows Server's security and directory for policy based security, acceleration and management of inter-networking. It can be integrated with an extensible, multi-layer enterprise firewall and a scalable high-performance Web cache.
Microsoft Commerce Server
Microsoft Commerce Server's main feature is to provide an application framework, sophisticated feedback mechanism and analytical capabilities for system integrations.
.NET platform is a technology that is specially designed to transform the Internet into a full-scale distributed computing platform, and also provides new ways to create applications from collections of Web Services. .NET platform is fully compatible and has support for a wide range of existing Internet infrastructures.
The main features of .NET platform are summarized as follows.
1. It is a language-independent with consistent programming model across applications.
2. Can be easily migrated from existing technologies and is fully compatible and interoperable between different technologies.
3. supports Internet's platform-neutral, standard-based technologies such as HTTP, XML and SOAP technologies
The technologies of .NET platform
.NET platform is useful and very important in Web application developments because it provides the Web application developers with specialized tools and technologies to build distributed Web applications with ease.
Basically, the .NET platform is made up of 4 core technologies, they are;
1. .NET framework
2. .NET Building Block Services,
3. .NET Enterprise Servers, and
4. Microsoft Visual Studio .NET
.NET Framework
The .NET framework is based on a new common language runtime. It is a runtime that is embedded in Visual Studio .NET and is language independent. That means, these common set of runtime services are used and shared by all .NET languages be it Microsoft Visual Basic, Visual C++ or other Microsoft programming languages. As such, an application developed in Visual Basic .NET does not need to distribute Visual Basic specific run-time libraries anymore. To simplify the application development further, all future Microsoft Windows will be equiped with these run-time libraries.
.NET Building Block Services
The .NET Building Block Services are distributed programmable services that are available whether online or offline. It is a building block service that can be used from any platform that supports SOAP technology such as identity, messaging, personalizations, calendar, search, notification and software delivery. It can be invoked through a stand-alone computer without Internet connection, provided a local server running inside a company, or accessed through the Internet.
.NET Enterprise Servers
The .NET Enterprise Servers are server features that provide enhanced scalability, reliability, management and integration within and across organizations.
Visual Studio .NET
Visual Studio .NET or VS.NET is a high level programming development environment for building applications to take advantage of the .NET Framework. It provides the seamless technologies and tools to easily develop, deploy and enhance web applications and services through highly secure, scalable and advanced technologies and features. In addition, it also enables the development of new generation Windows-based applications to become possible through ulitizing .NET framework features.
Using LCase Function in VB
LCase function is used to convert a string into lower case, therefore the name LCase. LCase can be used in your VB code as follows.
Dim myString As String '---Variable declaration
myString = "My house is on FIRE!" '--- initialize string data
myString = LCase(myString) '--- convert the string into lower case
MsgBox(myString) '--- result will become "my house is on fire!".
LCase converts all the upper case letters into lower case while lower case letters will remain intact.
See Also UCase Function
Using UCase Function in VB
UCase function is used to convert a string into UPPER CASE, hence the name UCase. UCase can be applied in your VB programming codes as follows.
Dim myString As String '---Variable declaration
myString = "My house is on FIRE!" '--- initialize string data
myString = UCase(myString) '--- convert the string into UPPER CASE
MsgBox(myString) '--- result is now "MY HOUSE IS ON FIRE"
UCase converts all the lower case letters into upper case while upper case letters will remain as it is.
See Also LCase Function
Using InStr Function in VB
InStr in VB.NET / VB6 is a very powerful method to search for the occurance of certain character or word in a string. You can use the InStr method in VB.NET / VB6 code as shown below. The result of using InStr will be in Integer form displaying the position that the string you find occurs at. myString is the string that you want to search against. FindString is the character or word you are finding in myString. OccurancePost is the position in which the finding is located.
OccurancePost = InStr(myString, FindString)
The simple example illustrated below shows how InStr method works in VB.
Dim OccurancePost As Integer '---Declare variables
Dim myString, FindString As String
myString = "Hello David! Welcome to the world" '--- the sentence
FindString = "David" '----- data to look for in the sentence
OccurancePost = Instr(myString, FindString) '--- InStr method
MsgBox(OccurancePost) '--- the result will be 7.
From the code above, we can see that the word David occurs at the 7th letter from the left (position 7) in the sentence. However, if the word that you intend to find does not appear in the sentence, InStr method will return a value of zero (0).
You can include the following code to cater for the case as below.
If OccurancePost = 0 Then
MsgBox("The word that you intend to look for cannot be found")
End If
That briefly explains how InStr works in VB.NET or VB6
VB.NET : Writing Multithreading Codes
Posted by Fluffy | 4:46 AM | VB.NET, Writing Multithreading Codes | 0 comments »Writing Multithreading codes in VB.NET
Implementing multithreading to your application is in fact very easy and simple. We will go through the example below to understand how multithreading works. Firstly, before you do anything, you have to include the namespace below into your project. Add it at the top of your project module.
Imports System.Threading.Thread
Next, you will have to add a BackgroundWorker component from the toolbox into your project as show below.

Then, add the 4 controls as shown in the figure below into an empty form and name them as follows.
BtnMT, BtnNonMT, TextBox1, ProgressBar1

After that, add the following codes (Copy & Paste) into your project.
Public Sub StartBackgroundWorker()
If BackgroundWorker1.IsBusy = True Then
MsgBox("Process already running, please wait.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
Else
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Protected Overridable Sub BackgroundWorkerJob_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
RunCount()
End Sub
Private Sub BackgroundWorkerJob_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.Text = "Process is running, Please Wait!"
End Sub
Protected Overridable Sub BackgroundWorkerJob_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Me.Text = "Process Finished."
End Sub
Private Sub RunCount()
Dim i As Integer
For i = 1 To 100
Sleep(500)
TextBox1.text = i & "%"
ProgressBar1.Value = i
Next
End Sub
Finally, add this code behind BtnMT button
Me.StartBackgroundWorker()
and this code behind BtnNonMT button
RunCount()
Now, start the application and click on MT button. Notice the result in the diagram below. While the separate thread is running the lengthy process, the user interface shows the progress and the TextBox1 shows the percentages completed.
Now, lets re-run the application and click on Non MT button this time. Both the lengthy process and the user-interface will be running under the same thread. See the result in the diagram below. Notice that without multithreading, the application stops responding after a while with the message showing Form1(Not Responding). Worst still, the application simply forgot to show the percentage completed in the TextBox1. Now, the user will have a hard time to know exactly when the process is going to finish.
Hope this simple multithreading example that i have created above helps you understand and let you know the difference between multithreading and non-multithreading applications.
Back To MultiThreading in VB.NET
MultiThreading in VB.NET
VB.NET has a very great feature called MultiThreading (MT) which is not available in classic VB. In the past, MultiThreading is only available and limited within C++ programming language development environment. Now with this great feature becoming part of VB.NET, you should fully utilize this feature as it allows you to separate your applications into multiple parts (threads), each handling different tasks.
Advantages of MultiThreading
The main advantage of multithreading is that it allows your application to work on many tasks at the same time. Sometimes it is also known that the application runs faster with multithreading as the time for each of the tasks is divided by the CPU and executed concurrently, thus greatly minimizes idle CPU time.
Multithreading is mainly used in applications with lengthy processes which involves sophisticated calculations where the CPU is utilized intensively. Usually, this lengthy process is run on a separate thread from the graphical user interface as the user can still be able to work on this user interface while the lengthy process is running. Hence, the application will not look dead as the user interface is still responding to the user request.
What happens if there is no MultiThreading
Without multithreading where both the lengthy process and the user interface is running under the same thread, this is what will happen. As soon as the user clicks on the button in the user interface to start the lengthy process, the entire user interface freezes. After a while, a non-responding message for this process will occur in the title bar as well as in the task manager.
Although the application is actually still running and the not responding message might not be true entirely, the user has to wait until the lengthy process finishes before the user interface comes back to life again. This also prohibits the user from using a progressbar in the application as it will not work since the user interface is already freezed. The user might not know or will not have any hints on when the lengthy process will finish.
Click the link below to see how you can implement Multithreading into your project.
See MultiThreading VB.NET sample codes here
Writing Subs In VB
Sub procedures are basic programming blocks that are used to call another section of codes from virtually anywhere in the project. It allows code reuse without having to rewrite the codes again everytime that piece of codes need to be used. Unlike Functions procedures, Subs do not need to return a value to the caller. Everytime a Sub procedure is called from a line of code, The entire piece of code in the Sub will be executed until the end before proceeding to the next line of code.
The example below illustrates how a Sub Procedure works
Public Sub DisplayMessage()
MsgBox("Hello, You Called Me")
End Sub
To call the DisplayMessage Sub procedure created above, just include a line as follows in your programming codes.
DisplayMessage()
That explains how A Sub procedure works in Visual Basic.
See Also How To Write A Function
VB : Fahrenheit To Celcius Converter Function
Posted by Fluffy | 5:32 AM | Fahrenheit To Celcius Converter Function, VB.NET, VB6 | 0 comments »Fahrenheit To Celcius Converter Function In VB
The VB codes below represents a Fahrenheit to Celcius converter function that you can use in your VB.NET or VB6 project.
Public Function FahrenheitToCelcius(ByVal Fahrenheit As Double) As Double
Dim Celcius As Double
Celcius = (Fahrenheit -32) * (5/9)
Return(Celcius)
End Function
Just copy the simple Fahrenheit To Celcius Converter Function above and paste it into your VB code to start converting.
See Also Celcius To Fahrenheit Converter
VB : Celcius To Fahrenheit Converter Function
Posted by Fluffy | 5:23 AM | Celcius To Fahrenheit Converter Function, VB.NET, VB6 | 0 comments »Celcius To Fahrenheit Converter Function In VB
The Visual Basic codes below represents a Celcius to Fahrenheit converter function that you can use in your VB.NET or VB6 project.
Public Function CelciusToFahrenheit(ByVal Celcius As Double) As Double
Dim Fahrenheit As Double
Fahrenheit = (Celcius * 9/5) +32
Return(Fahrenheit)
End Function
Copy and paste the simple Celcius To Fahrenheit Converter Function above into your Visual Basic code and start converting.
See Also Fahrenheit To Celcius Converter
Writing Functions in VB
Functions are very useful and convenient methods in programming. It is basically used to generate data by passing a data value into the function and then obtain a result from it. Like Sub procedure, a function is eclared with a Function keyword. See the example below on how to create a function.
Public Function Multiply(ByVal InputData As Double) As Double
Dim OutputData As Double
OutputData = InputData * 2
Return(OutputData)
End Function
As can be seen in the example above, The function is a 'Public' declaration type which means this function can be access from anywhere in the project. For instance, if this function is specifically created for access from within this module only, 'Private' type will be used instead. The next item Multiply is the name of this function. Further on, the ByVal InputData As Double section in the example above declares the input variable of this function. It is the entry point into the Function. The following As Double at the end of the function procedure is the declaration of the output data type, that is, the data that the function ultimately returns to the caller. Notice that inside the function, a Return() call exists and this is necessary as it is the exit point leading the way out the function.
Unlike Sub procedure which doesn't has an exit point, a function has at least an entry point and an exit point. If a function requires more than one input data, commas can be used to separate between the declaration of input data. See the second example illustrated below.
Public Function Multiply(ByVal InputData1 As Double, ByVal InputData2 As Double) As Double
Dim OutputData As Double
OutputData = InputData1 * InputData2
Return(OutputData)
End Function
To call the function above in your Visual Basic code, just add the following line as follows
TextBox1.Text = Multiply( 54 , 3 )
The value obtained in TextBox1.Text will be 162. Hence, that's how you can create functions in Visual Basic programming. It helps you better organize your programming code making it easier to read and best of all, Function can be reused again and again everywhere in your project.
See a function example on Fahrenheit To Celcius Converter
and also Celcius To Fahrenheit Converter
See Also Writing A Sub
Using CDec Function in VB
CDec is used to convert data into Decimal data type. The example below briefly illustrates how CDec function can be used in Visual Basic programming code.
Dim myData As Integer '--- Declare the variables
Dim Output As Decimal
myData = 79 '--- Initialize data value
Output = CDec((myData - 32) * (7 / 3) * (5 / 9)) '---Convert data into Decimal data type
MsgBox(Output) '-The output is 60.9259259259259
As can be seen in the above example illustration, there is technically no difference between conversion of the data into either Decimal data type or Double data type. The only difference that both the data type Decimal and Double is that Decimal has its value fixed at a base of 10 whereas Double is a floating point number base of 2. That is, they differs only in the precisions & ranges of the value.
See Also CType Function
VB : CType Manual Data Conversion
Posted by Fluffy | 5:51 AM | Manual Data Conversion, VB.NET, VB6 | 0 comments »Data Conversion in VB
To manually convert data in Visual basic, we can use the in-built function CType to perform the task. CType function is used to perform conversion of any value from one data type into another data type. However, if the value that you intend to convert into and the data type is outside of the value range allowed then an error might occur. The syntax for CType is show as follows
CType(Expression, NameOfDataType)
The NameOfDataType can be any expression that is valid within As clause in a Dim statement, name of any datatype, class, object structure or even interface. The example below shows how CType can be used in VB programming.
Dim myString As String '--- Variable Declaration
Dim myNumber As Integer
myString ="5469" '---Initialize string
myNumber = CType(myString, Integer) '--- convert string to integer
MsgBox(myNumber) '--- Result myNumber will be integer 5469
CType function is rather similar to the other functions used in VB6 like the ones listed below, These functions are used to convert data into the following data type as listed on the right side.
CBool - Boolean
CByte - Byte
CChar - Char
CDate - Date
CDbl - Double
CDec - Decimal
CInt - Integer
CLng - Long
CSng - Single
CStr - String
Hence, that shows how data conversion can be done manually by using CType functions.
Using CStr function in VB
CStr is a function that is used to convert data into the String data type. See the example below on how this CStr function can be used in Visual Basic programming.
Dim myData1 As Double '---Variable declaration
Dim myData2 As Boolean
Dim Output1, Output2 As String
myData1 = 5469.2641 '---Initialization of data
myData2 = False
Output1 = CStr(myData1) '--- convert data into String data type
Output2 = CStr(myData2)
MsgBox(Output1) '---Output is '5469.2641'
MsgBox(Output2) '---Output is 'False'
However, if a Date value is converted, the result will always be in short date format. Also note that if a Null value is being converted, a run-time error might occur. Hope that helps you understand how CStr function works and how you can apply it in your Visua Basic code.
See Also CType Function
Using CLng function in VB
CLng is a function that is used to convert data into Long data type. It is basically used to round figures with multiple decimal points. See the example shown below.
Dim myData1, myData2 As Double '---Variable declaration
Dim Output1, Output2 As Long
myData1 = 5469.61 '---Initialization of data
myData1 = 5469.48
Output1 = CLng(myData1) '--- convert data into Long data type
Output2 = CLng(myData2)
MsgBox(Output1) '---Output is 5470
MsgBox(Output2) '---Output is 5469
However, there is also one interesting thing to note that this CLng function rounds figures to the nearest even number, that is (0,2,4,6,8) if the fraction part of a multi-decimal point figure is exactly 0.5. See the second example below to properly illustrate this special feature.
Dim myData1, myData2 As Double '---Variable declaration
Dim Output1, Output2 As Long
myData1 = 5464.5 '---Initialization of data
myData1 = 5475.5
Output1 = CLng(myData1) '--- convert data into Long data type
Output2 = CLng(myData2)
MsgBox(Output1) '---Output is 5464
MsgBox(Output2) '---Output is 5476
Note that conversion of 5464.5 in Output1 becomes 5464 instead of 5465 because 5464 is the nearest even number whereas 5465 is an odd number. The same applies to Output2 as well. Therefore, that illustrates the concept of applying CLng function into your VB programming code.
See Also CType Function
Using CInt function in VB
CInt is a function that is used for converting data to Integer data type. It is normally used in circumstances where double-precision, single-precision, currency and other multi-decimal points figures occur. The simple example below shows how CInt can be applied in Visual Basic codes.
Dim myData As Double '-----Declaration of variable
Dim Output As Integer
myData= 5469.855 '----- Initialization of data
Output = CInt(myData) '----convert myData into Integer
MsgBox(Output) '----- output data is 5470
Hence, the result above shows the conversion from a Double data type into Integer Data type using CInt.
See Also CType Functions
Using CSng function in VB
CSng is a function that is used to convert a data to Single data type. Unlike CDbl which forces double-precision, CSng is only a single-precision data type. See the example shown below on how CSng works.
Dim MyData1, MyData2 As Double '--- Declares Variable
Dim Output1, Output2 As Single
MyData1 = 43.982865935 '--- Initialize data
MyData2 = 853719.4588613
Output1 = CSng(MyData1) '--- Convert MyData1 into Single data type
Output2 = CSng(MyData2) '--- Convert MyData1 into Single data type
MsgBox(Output1) '--- Output1 is 43.98286
MsgBox(Output2) '--- Output2 is 853719.4
As can be seen in the result above, only a fixed number of digits is shown in the output even though the original figures has more. Thus, that shows how CSng is applied in Visual Basic programming.
See Also CType Functions
Using CDbl Function in VB
CDbl function is used to convert a data into Double data type. See the simple example illustrated below for a better understanding of this CDbl function. The example below converts a data stored in a textbox and convert it into Double data type.
Dim Output As Double '---- Declaring Variable
TextBox1.Text = "234.456784" '--- Initialize the figure as a string stored in a textbox
Output = CDbl(Val(TextBox1.Text) * 3.142 * 10/100) '- Run the formula of multiplying the figure with pi, and then multiply it again by 10%.
MsgBox(Output) '-- The output retrieved will be 73.6663215328
Hope you could now be able to know how you can use this CDbl function and apply in your VB codes.
See Also CType Functions
Using CDate Function in VB
CDate function is used to convert a data into date data type. The example below illustrate how you can convert a date from a textbox into a date data type.
Dim Output As Date '----Declare Variables
TextBox1.Text = "January 20, 2009" '---- Initialize date in the textbox.
Output = CDate(TextBox1.Text) ' Convert the string to Date data type.
MsgBox(Output) '----The output is 20-Jan-09
That's how date is converted in using CDate function in your VB programming code.
See Also CType Functions
Using CByte function in VB
CByte function can be used to force byte arithmetic where multi-decimal figures are present. The following example below shows how to convert a dollar value derived from currency exchange.
Assuming we are converting 1o Euro to US Dollar using an exchange rate of 1 Euro = 1.3864 USD
Dim ExchangeRate As Double '---Variables declaration
Dim Euro, USD As Double
Dim Output As Byte
Euro = 10 '---- 10 Euro
ExchangeRate = 1.3864 '----Initialize exchange rate value
USD = Euro * ExchangeRate '---- This will gives you a figure of 13.854 in US dollar term
Output = CByte(USD) '--- Convert the data to byte arithmetic
MsgBox(Output) '---- Output value becomes 14 US Dollar
Hence, that shows how you can implement CByte function in your Visual Basic programming
See Also CType Functions
Using CBool function in VB
CBool function is used to convert data into boolean data type. The example below briefly shows how you can apply this CBool function into your programming code.
Dim myData1, myData2 As Integer '--- Variables declaration
Dim Output as Boolean
MyData1 = 3 '--Initialization of data
MyData2 = 5
Output = CBool(MyData1 + MyData2 = 8) 'Check whether MyData1+MyData2 = 8
Msgbox(Output) ' Return output as TRUE
CBool function only returns a value of either TRUE or FALSE. Hence, that shows how CBool functions can be applied in programming
See Also CType Functions
Data Conversions in Visual Basic.
In many cases, Visual Basic is able to perform automatic data conversions on the data it executed during runtime, but certain times when the automatic conversion of data is impossible, especially in cases which involve conversion of dates, a manual conversion is required.
To simulate an example on how visual basic can identify and converts data automatically, take a look at the simple codes below.
Dim myData As Double '---Variables declaration
Dim CvtData As Integer
myData = 9800.4523 '--- store data into myData variable as data type "Double"
CvtData = myData '----transfer the data from myData into CvtData
MsgBox(CvtData) '--- Output data becomes 9800
The simple code above illustrates that the Visual Basic has automatically converted the data from Double into Integer data type. Now take a look at the second sample code below.
Dim CvtData as Integer '---Variables declaration
Dim TextData As String
CvtData = 9800 '--- store previous examples data
TextData = CvtData '----transfer the data from CvtData into TextData
MsgBox(TextData) '--- Now the output data '9800' has become a string
Like the first example, Visual Basic has again automatically converted the data from Integer into String data type. If Visual Basic is unable to automatically convert the data, then a manual data conversion can be done by using the built-in Cast (CType) function.
See How To Perform Manual Data Conversion Using CType Function
Formating Numbers in Visual Basic
In Visual Basic you can easily format numbers the way you want it to be displayed by using the format() function. Format(expression, format) applying the following symbols ('#') (',') ('0')
'#' symbol represents that a number in this position will be displayed if the number is available and is greater than zero. '0' on the other hand represents that a number in this particular position will be displayed even if it is not available. Lastly ',' is used as a separator for thousands or millions and so on. See the example below to have a better understanding on how to apply this format function in your programming code.
'---Displaying figures in textbox1.text
Dim MyNumber1, MyNumber2, MyNumber3 As Double
MyNumber1 = 4985746.3
MyNumber2 = 0.48
MyNumber3 = 3142
textbox1.text = Format(MyNumber1, "#,###,##0.00") 'displayed as : 4,985,746.30
textbox1.text = Format(MyNumber1, "######0.00") 'displayed as : 4985746.30
textbox1.text = Format(MyNumber1, "######0.0000") 'displayed as : 4985746.3000
textbox1.text = Format(MyNumber2, "#,###.00") 'displayed as : 0.48
textbox1.text = Format(MyNumber2, "####.00") 'displayed as : 0.48
textbox1.text = Format(MyNumber2, "#,##0.00") 'displayed as : 0.48
textbox1.text = Format(MyNumber2, "###0.0") 'displayed as : 0.4
textbox3.text = Format(MyNumber3, "###0.0") 'displayed as 3142.0
textbox3.text = Format(MyNumber3, "###0.0000") 'displayed as 3142.0000
textbox3.text = Format(MyNumber3, "####.00") 'displayed as 3142.00
textbox3.text = Format(MyNumber3, "####.##") 'displayed as 3142
textbox3.text = Format(MyNumber3, "#,###.##") 'displayed as 3,142
That explains how number formatting works in Visual Basic.
Contact
Name : Daniel Tant
Location : Allentown Metro Area, Lehigh County
Pennsylvania, United States.
Email : danieltant@usa.com
About VB Egg
Your Ultimate Visual Basic 6, VB Classic, VB.NET and VBx information, guide and other resources site.
VB Egg, U.S.A. Copyright (C) 2009. All rights reserved.
Created by Daniel Tant specially for your educational and reference purposes.
VB.NET : Add Project Reference
Posted by Fluffy | 3:34 AM | Add Project Reference VB.NET, VB.NET | 0 comments »Adding Project Reference In VB.NET
Sometimes, you need to insert additional references for certain functions that you might need to use during your VB.NET application development. Adding a project reference to your application project is easy. Basically all you have to do is just follow the 5 simple steps below.
1. Go to the menu, Select Project and then click on Properties
2. A Window will pop-up. Choose References from the tabs on the left hand side of the window.
3. Click the Add button in the window
4. An Add Reference window will now prompt. Select the component that you want to add and then click OK.
5. Done. Repeat from step 3 again if you want to add another project reference.
You should now be able to use the various components after adding the project references.
VB.NET : Write Data Into A Text File
Posted by Fluffy | 3:25 AM | VB.NET, Write Data Into A Text File VB.NET | 0 comments »Write Data Into A Text File Using VB.NET
The example below shows how you can open a textfile ( .txt) and write the data by using VB.NET. Assuming the text file "contact.txt" stored in C:\ drive contains the following 3 lines (Name, Contact Number and Address)
----------------------contact.txt---------------------
Kimberly Wood
570-897-7676227
Main Avenue PO Box 987, Palmerton, PA 18071
------------------------------------------------------
The codes below show you how to write these data into a text file using VB.NET. You might need to include System.IO in your project reference section before you can execute the code.
'-----declare Variables
Dim Name, ContactNo, Address As String
Dim fs as New FileStream("C:\contact.txt", FileMode.Create, FileAccess.Write)
Dim ws as New StreamReader(fs)
ws.WriteLine(Name) '--- Write Name into Line 1
ws.WriteLine(ContactNo) '--- Write Name into Line 2
ws.WriteLine(Address) '--- Write Name into Line 3
ws.Close()
Hence, the three lines of data from the text file have been written and stored in the text file.
See Also How To Read Data From A Text File using VB.NET
See Also How To Read Data From A Text File using VB6 / Classic
See Also How To Write Data Into A Text File using VB6 / Classic
VB.NET : Left Function Equivalent
Posted by Fluffy | 6:06 AM | Left Function VB.NET, VB.NET | 0 comments »Using the Equivalent of Left Function in VB.NET
As VB.NET no longer supports the handy Left Function anymore, you can however, use the equivalent function code that i have created below. I have named the function as sLeft since Left conflicts with another function in VB.NET. Just copy and paste the simple codes at the bottom of your project module or form.
'---Copy and Paste this piece of code into your module or project
Public Function sLeft(ByVal iString As String, ByVal Position As Integer) As String
Return Mid(iString, 1, Position)
End Function
Now, for instance, we have a string "Spaceship" stored in a variable myStr
'--- Variable Declarations
Dim myStr As String
Dim Output as String
myStr = "Spaceship" '--- Store the word Spaceship into myStr
Output = sLeft(myStr,5) '---call sLeft function to retrieve the first 5 letters of the string
Msgbox(Output) '--- Display a messagebox
The output from the message above will be "Space"
See also Mid Function in VB.NET
See also Right Function in VB.NET
See also Left Function in VB6/Classic
See also Mid Function in VB6/Classic
See also Right Function in VB6/Classic
VB.NET : Right Function Equivalent
Posted by Fluffy | 5:44 AM | Right Function VB.NET, VB.NET | 0 comments »Using the Equivalent of Right Function in VB.NET
As VB.NET no longer supports the handy Right Function anymore, the sweet old days of using this Right function in VB6 programmings are already over. However, you can use the equivalent function code that i have created below. I have named the function as sRight since Right conflicts with another function in VB.NET. Just copy and paste this simple codes at the bottom of your project module or form.
'---Copy and Paste this piece of code into your module or project
Public Function sRight( ByVal iString As String, ByVal Position as Integer) As String
Return Mid(iString,(len(iString)+1) - Position , Position)
End Function
Now, for instance, we have a string "Spaceship" stored in a variable myStr
'--- Variable Declarations
Dim myStr As String
Dim Output as String
myStr = "Spaceship" '--- Store the word Spaceship into myStr
Output = sRight(myStr,4) '---call sRight function to retrieve the last 4 letters of the string
Msgbox(Output) '--- Display a messagebox
The output from the message above will be "ship"
See also Left Function in VB.NET
See also Mid Function in VB.NET
See also Left Function in VB6/Classic
See also Mid Function in VB6/Classic
See also Right Function in VB6/Classic
Using Mid Function in VB.NET
Just like VB6 Mid function, the middle section of a string can be splitted at specific points.
It works the same way as in VB6.
To show an example, let's say we have a string "Laptop Computers" stored in a variable myStr and we will use Mid function to retrieve a few letters from the string.
'--- Variable Declarations
Dim myStr As String
Dim Output as String
myStr = "Laptop Computers" '--- Store the word Spaceship into myStr
Output = Mid(myStr,4,8) '---Retrieve 8 letters starting from the 4th letters counting from left
Msgbox(Output) '--- Display a messagebox
The output from the message above will be "top Comp"
See also Left Function in VB.NET
See also Right Function in VB.NET
See also Left Function in VB6/Classic
See also Mid Function in VB6/Classic
See also Right Function in VB6/Classic
Using Mid Function in VB6/Classic
VB6 Mid function is a string handling function whereby the middle section of a string can be splitted at specific points.
For Example, we have a string "Spaceship" stored in a variable myStr and we will use Mid function to split it.
'--- Variable Declarations
Dim myStr As String
Dim Output as String
myStr = "Spaceship" '--- Store the word Spaceship into myStr
Output = Mid(myStr,3,4) '---Retrieve 4 letters starting from the 3rd letters counting from left
Msgbox(Output) '--- Display a messagebox
The output from the message above will be "aces"
See also Left Function in VB.NET
See also Mid Function in VB.NET
See also Right Function in VB.NET
See also Left Function in VB6/Classic
See also Right Function in VB6/Classic
Using Right Function in VB6/Classic
VB6 Right function is a string handling function whereby the back section of a string can be splitted at specific points.
For Example, we have a string "Spaceship" stored in a variable myStr and we will use Right function to split it from the right side.
'--- Variable Declarations
Dim myStr As String
Dim Output as String
myStr = "Spaceship" '--- Store the word Spaceship into myStr
Output = Right(myStr,4) '---Retrieve the back 4 letters
Msgbox(Output) '--- Display a messagebox
The output from the message above will be "ship"
See also Left Function in VB.NET
See also Mid Function in VB.NET
See also Right Function in VB.NET
See also Left Function in VB6/Classic
See also Mid Function in VB6/Classic
Using Left Function in VB6/Classic
VB6 Left function is a string handling function whereby a front section of a string can be splitted at specific points.
For Example, we have a string "Spaceship" stored in a variable myStr and we will use Left function to split it from the left side.
'--- Variable Declarations
Dim myStr As String
Dim Output as String
myStr = "Spaceship" '--- Store the word Spaceship into myStr
Output = Left(myStr,5) '---Retrieve the front 5 letters
Msgbox(Output) '--- Display a messagebox
The output from the message above will be "Space"
See also Left Function in VB.NET
See also Mid Function in VB.NET
See also Right Function in VB.NET
See also Mid Function in VB6/Classic
See also Right Function in VB6/Classic
VB File I/O operations
Posted by Fluffy | 12:14 AM | VB.NET, VB6, Visual Basic File I/O operations | 0 comments »VB File Input/Output Operations.
VB supports file I/O operations by allowing reading and writing data into files be it in your hard drive or even removable disks. They are very important functions particularly in applications that requires the storing of user preference, user settings such as video resolution, sound effects and configuration files. These are very useful as the user can load these preferred settings back whenever the application is executed.
The data file used can be of any file extension type and it can also be no extension at all. But typically, programmers will use the following extensions to symbolize the information stored.
".cfg" for configurations and settings
".dat" for storing plain data
".txt" for storing data as text (by default can be edited in notepad)
See these examples below by clicking the links on how you use program the file operations in your Visual Basic application development.
VB6 / Classic Examples:
Read Data From A Text File Using VB6/ Classic
Write Data Into A Text File Using VB6 / Classic
VB.NET Examples:
Read Data From A Text File using VB.NET
Write Data Into A Text File using VB.NET
VB.NET : Read Data From A Text File
Posted by Fluffy | 3:02 AM | Read Data Into A Text File VB.NET, VB.NET | 0 comments »Read Data From A Text File Using VB.NET
The example below shows how you can open a textfile ( .txt) and read the data by using VB.NET. Assuming the text file "contact.txt" stored in C:\ drive contains the following 3 lines (Name, Contact Number and Address)
----------------------contact.txt---------------------
Kimberly Wood
570-897-7676227
Main Avenue PO Box 987, Palmerton, PA 18071
------------------------------------------------------
See the example shown below on how to read these data using VB.NET. You might need to include System.IO in your project reference section before you can execute the code.
'-----declare Variables
Dim Name, ContactNo, Address As String
Dim fs as New FileStream("C:\contact.txt", FileMode.Open, FileAccess.Read)
Dim wr as New StreamReader(fs)
wr.BaseStream.Seek(0, SeekOrigin.Begin) '---Go to beginning of file
Name &= wr.ReadLine '--- Read Line 1 data into variable Name
ContactNo &= wr.ReadLine '--- Read Line 1 data into variable ContactNo
Address &= wr.ReadLine '--- Read Line 1 data into variable Address
wr.Close()
At last, the three line of data from the text file is now read and stored into the three variables Name, ContactNo and Address variable in the program.
See Also How To Write Data Into A Text File using VB.NET
See Also How To Read Data From A Text File using VB6 / Classic
See Also How To Write Data Into A Text File using VB6 / Classic
VB6 : Write Data Into A Text File
Posted by Fluffy | 8:49 PM | VB6, Write Data Into A Text File VB6 | 0 comments »Write Data Into A Text File Using VB6 / Classic
The following example shows how you can write the following three lines of data into a textfile ( .txt) using Visual Basic. Assuming the text file "contact.txt" is to be stored in C:\ drive.
----------------------contact.txt---------------------
Michael Dee
880-488-7178887
789 Island Street, PO Box 88, Hamburg, PA 19526
------------------------------------------------------
Dim FileNum As Integer
Dim data As String
FileNum = FreeFile
On Error Goto ErrorHandler
Open "C:\contact.txt" For Output As #FileNum '---Create (if not exists) / Open file for writing
data = "Michael Dee"
Print #filenum, data '---Write line 1
data = "880-488-7178887 "
Print #filenum, data '---Write line 2
data = "789 Island Street, PO Box 88, Hamburg, PA 19526"
Print #filenum, data '---Write line 3
ErrorHandler:
Close #filenum '---Close the file after writing
Now the three line of data has been written and stored into the text file in Visual Basic.
See also how to Read Data From A Text File Using VB6 / Classic
See also how to Read Data From A Text File Using VB.NET
See also how to Write Data Into A Text File Using VB.NET
VB6 : Read Data From A Text File
Posted by Fluffy | 8:18 PM | Read Data From A Text File VB6, VB6 | 0 comments »Read A Text File using VB6 / Classic
The following example shows how you can open a textfile ( .txt) and read the data by using Visual Basic. Assuming the text file "contact.txt" stored in C:\ drive contains the following 3 lines (Name, Contact Number and Address)
----------------------contact.txt---------------------
Kimberly Wood
570-897-7676
227 Main Avenue PO Box 987, Palmerton, PA 18071
------------------------------------------------------
Now, to read the following three lines of data in visual basic, use the example shown below
'-----declare variables
Dim ReadData As String
Dim FileNum As Integer
Dim Name As String
Dim ContactNo As String
Dim Address As String
FileNum = FreeFile
On Error GoTo ErrorHandler
Open "C:\contact.txt" For Input As #filenum '---Open the file for reading
Input #filenum, ReadData '---read line 1
Name = ReadData '-----store data into variable Name
Input #filenum, ReadData '---read line 2
ContactNo = ReadData '-----store data into variable ContactNo
Input #filenum, ReadData '---read line 3
Address = ReadData '-----store data into variable Address
ErrorHandler:
Close #filenum '---Close the file after reading
Finally, the three line of data from the text file is now read and stored into the three variables Name, ContactNo and Address in Visual Basic.
See also how to Write Data Into A Text File Using VB6 / Classic
See also how to Read Data From A Text File Using VB.NET
See also how to Write Data Into A Text File Using VB.NET


