Professional Documents
Culture Documents
Livro VB Net Ado
Livro VB Net Ado
NET
2005
What is a Program?
An organized list of instructions that, when executed,
causes the computer to behave in a predetermined manner. Without programs, computers are useless.
A program is like a recipe. It contains a list of ingredients (called variables) and a list of directions (called statements) that tell the computer what to do with the variables. The variables can represent numeric data, text, or graphical images.
What is Programming?
A programming language is an artificial language that can be used to control the behavior of a computer. Source code is any series of statements written in a programming language. Computer Programming is the art of making a computer do what you want it to do.(often shortened to programming or coding) is the process of writing, testing, and maintaining the source code of computer programs.
Event-driven Programming
In computer programming, Event-Driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events Ex: sensor outputs or user actions (mouse clicks, key presses) or messages from other programs or threads.
Object-oriented programming
Object-oriented programming (OOP) is a programming
model that uses "objects" data structures consisting of data fields and methods and their interactions to design applications and computer programs. Programming techniques may include features such as, 1. 2. 3. 4. 5. Information hiding, data abstraction, encapsulation, modularity, polymorphism, and inheritance.
It was not commonly used in mainstream software application development until the early 1990s. Many modern programming languages now support OOP.
Emphasis on data rather than procedure Programs are divided into Objects Data is hidden and cannot be accessed by external functions Objects can communicate with each other through functions New data and functions can be easily added whenever necessary Follows bottom-up approach
Concepts of OOP:
1. Objects 2. Classes 3. Data Abstraction and Encapsulation 4. Inheritance 5. Polymorphism
Objects
Objects are the basic run-time entities in an object-oriented system. Programming problem is analyzed in terms of objects and nature of communication between them. When a program is executed, objects interact with each other by sending messages. Different objects can also interact with each other without knowing the details of their data or code. Dog(Object)
Attributes
Skin color Eye color Height Weight Etc.
Behaviors
Eat Bark Run Jump Etc.
Classes
A class is a collection of objects of similar type. Once a class is defined, any number of objects can be created which belong to that class.
SON MALE
FATHER
ENCAPSULED
Inheritance
Inheritance is the process by which objects can acquire the properties of objects of other class. In OOP, inheritance provides reusability, like, adding additional features to an existing class without modifying it. This is achieved by deriving a new class from the existing one. The new class will have combined features of both the classes.
Polymorphism
Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance.
Rectangle Shape
Triangle
Software development life cycle model is also called as waterfall model which is followed by majority of systems. This software development life cycle process has the following seven stages in it namely 1. System Requirements Analysis 2. Feasibility study 3. Systems Analysis and Design 4. Code Generation 5. Testing 6. Maintenance 7. Implementation
2. Feasibility study:
After making an analysis in the system requirement the next step is to make analysis of the software requirement. In other words feasibility study is also called as software requirement analysis. In this phase development team has to make communication with customers and make analysis of their requirement and analyze the system. By making analysis this way it would be possible to make a report of identified area of problem. By making a detailed analysis on this area a detailed document or report is prepared in this phase which has details like project plan or schedule of the project, the cost estimated for developing and executing the system, target dates for each phase of delivery of system developed and so on. This phase is the base of software development process since further steps taken in software development life cycle would be based on the analysis made on this phase and so careful analysis has to be made in this phase.
4. Code Generation:
This is the phase where actual development of the system takes place. That is based on the design documents prepared in the earlier phase code is written in the programming technology chosen. After the code is developed generation of code also takes place in this phase. In other words the code is converted into executable in this phase after code generation.
5. Testing:
A software or system which is not tested would be of poor quality. This is because this is the phase where system developed would be tested and reports are prepared about bugs or errors in system. To do this testing phase there are different levels and methods of testing like unit testing, system test and so on. Based on the need the testing methods are chosen and reports are prepared about bugs. After this process the system again goes to development phase for correction of errors and again tested. This process continues until the system is found to be error free. To ease the testing process debuggers or testing tools are also available.
6. Maintenance:
After the testing phase is completely through and the system is found to be error free it is delivered to the customer. But no real system would be error free even then. This is because when the system gets executed in real user system scenarios there would be possibilities of lot of bugs and errors. This phase is called the maintenance phase and the errors in this are recorded and changes has to be made in the system accordingly and again testing phase comes into picture.
7. Implementation:
This is the final stage when the system gets into live. The above software development process are all vital for a system to get developed with quality and thus to achieve customer satisfaction which is the main objective of any software development process.
Objects
An object is an entity which has a state and a defined set of operations which operate on that state. The state is represented as a set of object attributes. The operations associated with the object provide services to other objects (clients) which request these services when some computation is required. Objects are created according to some object class definition. An object class definition serves as a template for objects. It includes declarations of all the attributes and services which should be associated with an object of that class.
Solution Explorer
Tool Box
Property Window
The Form Window is central to developing Visual Basic applications. It is where you draw your application.
The Toolbox is the selection menu for controls used in your application.
The Properties Window is used to establish initial property values for objects. The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized. Under this box are the available properties for the currently selected object
Solution Explorer provides you with an organized view of your projects and their files as well as ready access to the commands that pertain to them. A toolbar associated with this window offers commonly used commands for the item you highlight in the list. To access Solution Explorer, select Solution Explorer on the View menu.
Code editor allows user to write and maintain the code related to the solution Class name list Method name list
Naming Objects
Control type Check box Combo box, drop-down list box Command button Form Label List box ListView Option button Picture box RichTextBox Text box Timer prefix chk cbo cmd frm lbl lst lvw opt pic rtf txt tmr Example chkReadOnly cboEnglish cmdExit frmEntry lblHelpMessage lstPolicyCodes lvwHeadings optGender picVGA rtfReport txtLastName tmrAlarm
The following table contains a listing of the Visual Basic .NET language keywords. All language keywords are reserved.
AddHandler AndAlso Auto ByVal CBool CDec Class CShort Date Delegate Double End Event For GetType If Inherits AddressOf Ansi Boolean Call CByte CDbl CLng CSng Decimal Dim Each Enum Exit Friend GoSub Implements Integer Alias As ByRef Case CChar Char CObj CStr Declare DirectCast Else Erase False Function GoTo Imports Interface And Assembly Byte Catch CDate CInt Const CType Default Do ElseIf Error Finally Get Handles In Is
Let Loop MustInherit Namespace Nothing On OrElse ParamArray Protected ReDim Return Shared Step Sub To Unicode While Xor #Region * \ +
Lib Me MustOverride New NotInheritable Option Overloads Preserve Public REM Select Short Stop SyncLock True Until With #Const *= \= +=
Like Mod MyBase Next NotOverridable Optional Overridable Private RaiseEvent RemoveHandler Set Single String Then Try Variant WithEvents #ExternalSource & / ^ =
Long Module MyClass Not Object Or Overrides Property ReadOnly Resume Shadows Static Structure Throw TypeOf When WriteOnly #If...Then...#Else &= /= ^= -=
Variables
With Visual Basic, and most programming languages, what you are doing is storing things in the computer's memory, and manipulating this store. If you want to add two numbers together, you put the numbers into storage areas and "tell" Visual Basic to add them up. But you can't do this without variables.
1. No more than 40 characters 2. They may include letters, numbers, and underscore (_) 3. The first character must be a letter 4. You cannot use a reserved word (word needed by Visual Basic)
Now examine this: Dim number1 As Integer Dim number 2 As Integer number1 = 3 number2 = 5
Dim Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you are setting up a variable with this word. number1 This is a variable. In other words, our storage area. After the Dim word, Visual Basic is looking for the name of your variable. You can call your variable almost anything you like As Integer We're telling Visual Basic that the variable is going to be a number (integer). Number1 = 3 The equals sign is not actually an equals sign. The = sign means assign a value of. In other words, here is where you put something in your variable. We're telling Visual Basic to assign a value of 3 to the variable called number1.
Decimal
16
Data Type Boolean Integer Long (Integer) Single (Floating) Double (Floating) Currency Date Object String Variant
Variable Declaration
There are three ways for a variable to be typed (declared): 1. Default 2. Implicit 3. Explicit If variables are not implicitly or explicitly typed, they are assigned the variant type by default. The variant data type is a special type used by Visual Basic that can contain numeric, string, or date data.
To implicitly type a variable, use the corresponding suffix shown above in the data type table. For example,
Dim <Variable name> $ = "This is a string" //creates a string variable, while Dim <Variable name> % = 300 //creates an integer variable.
There are many advantages to explicitly typing variables. Primarily, we insure all computations are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names. Because of these advantages, and because it is good programming practice, we will explicitly type all variables. To explicitly type a variable, you must first determine its scope.
1. 2. 3. 4.
Procedure level Procedure level, static Form and module level Global level
Within a procedure, variables are declared using the Dim statement: Dim <Variable name> as Integer Dim <Variable name> as Double Dim <Variable name> , <Variable name> as String
Procedure level variables declared in this manner do not retain their value once a procedure terminates. To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static:
Form (module) level variables retain their value and are available to all procedures within that form (module). Form (module) level variables are declared in the declarations part of the general object in the forms (module's) code window. The Dim keyword is used:
Public level variables retain their value and are available to all procedures within an application. Module level variables are declared in the declarations part of the general object of a module's code window. (It is advisable to keep all Public variables in one module.) Use the Public keyword:
String Variables
What is a String? Actually a string is nothing more than text. And if we want Visual Basic to store text we need to use the word "String". To set up a variable to hold text we need to use As String and not As Integer. If the information we want to store in our variables is a First Name and a Last Name, we can set up two variables like this.
Arrays
An array is a collection of values of the same data type. The values in an array are called array elements. Array elements are accessed using a single name and an index number representing the position of the element within the array. An array is a standard structure for storing data in any programming language. Variables can hold single entities, such as one number, one date, or one string and arrays can hold sets of data of the same type (a set of numbers, a series of dates, and so on). An array has a name, and the values stored in it can be accessed by an index.
Declaring Arrays Unlike simple variables, arrays must be declared with the Dim (or Public, or Private) statement followed by the name of the array and the index of the last element in the array in parentheses for example: Dim Ages(19) As Integer
Initializing Arrays
Just as we can initialize variables in the same line where we declare them, we can initialize arrays too, with the following constructor: Heres an example that initializes an array of strings: Dim names() As String ("john", "Sam","Hedric") This statement is equivalent to the following statements, which declare an array with two elements and then set their values: Dim names(2) As String names(O)="John" names(1) ="Sam" names(2) ="Hedric" The number of elements in the curly brackets following the arrays declaration determines the dimensions of the array, and we cant add new elements to the array without resizing it.
Multidimensional Arrays
Arrays can be multidimensional. Multidimensional arrays can be thought of as arrays-ofarrays. For example, to visualize a two dimensional array we could picture a row of CD racks. To make things easier, we can imagine that each CD rack could be for a different artist. Like the CDs, the racks would be identifiable by number. Below we'll define a two dimensional array representing a row of CD racks. The strings inside of the array will represent album titles.
' Here we will define an array where the first dimension contains 2 elements and the second dimension contains 4 elements Dim cdRack(1,3) As String
' A CD rack for the Beatles cdRack(0, 0) = "Rubber Soul" cdRack(0, 1) = "Revolver" cdRack(0, 2) = "The White Album" cdRack(0, 3) = "Let It Be
1
Revolver Beggars Banquet
2
The White Album
3
Let It Be
0
1
' A CD rack for the Rolling Stones cdRack(1, 0) = "Sticky Fingers" cdRack(1, 1) = "Beggars Banquet" cdRack(1, 2) = "Let It Bleed" cdRack(1, 3) = "Tattoo You"
Operators
Operators
Visual Basic comes with many built-in operators that allow us to manipulate data. An operator performs a function on one or more operands. For example, we add two variables with the "+" addition operator and store the result in a third variable with the "=" assignment operator like this: int x + int y = int z. The two variables (x ,y) are called operands. There are different types of operators in Visual Basic
1. Arithmetic Operators
2. Concatenation Operators
3. Comparison Operators 4. Logical / Bitwise Operators
Arithmetic Operators Arithmetic operators are used to perform arithmetic operations that involve calculation of numeric values. The table below summarizes them:
Operator ^ * /
Use Exponentiation Negation (used to reverse the sign of the given value, exp -intValue) Multiplication Division
\
Mod + -
Integer Division
Modulus Arithmetic Addition Subtraction
Example
Dim x, y, z As Integer x = 30 y = 20 z=x+y MessageBox.Show(z) z=x-y MessageBox.Show(z) z=x*y MessageBox.Show(z) z=x/y MessageBox.Show(z)
Concatenation Operators
Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & as summarized below:
Dim str1, str2, str3, str4 As String str1 = "Concatenation" str2 = "Operators" str3 = str1 + str2 MessageBox.Show(str3) str4 = str1 & str2 MessageBox.Show(str4)
Comparison Operators A comparison operator compares operands and returns a logical value based on whether the comparison is true or not. The table below summarizes them:
Use Equality Inequality Less than Greater than Greater than or equal to
<=
Example
Dim x, y As Integer x = 10 y = 15 If x = y Then MessageBox.Show ("x is Equal to y") ElseIf x < y Then MessageBox.Show("x is less than y") ElseIf x > y Then MessageBox.Show("x is greater than y") End If
Logical / Bitwise Operators The logical operators compare Boolean expressions and return a Boolean result. In short, logical operators are expressions which return a true or false result over a conditional expression. The table below summarizes them:
The Not operator The Not operator will return the opposite of the Boolean value, Not True will return False and Not False will return True. See the example below: Dim P As Boolean = False MessageBox.Show(Not P)
The And operator The And operator will check if two boolean values are true. Both needs to True or the And operator won't return true. See the examples below: Dim P, Q As Boolean P = True Q = False MessageBox.Show(P And Q)
The Or operator For the Or operator to return True, at least one of the values have to be True. If both are True doesn't matter, it will also return True. Look at this example below: Dim P, Q As Boolean P = True Q = False MessageBox.Show(P Or Q) The Xor operator The Xor operator will return True if and only if one of the values are True. This means that the different between Or and Xor is that if both values are True, Or will return True but Xor will return False, See this example: Dim P, Q As Boolean P = False Q = False MessageBox.Show(P Xor Q)
Console Applications
Console Applications are command-line oriented applications that allow us to read characters from the console, write characters to the console and are executed in the DOS version. Console Applications are written in code and are supported by the System.Console namespace. Example on a Console Application
Dim I as Integer
What is a Function ?
A function is a segment of code that accepts zero, one or more arguments and returns a single result. Some perform basic mathematical tasks. Others manipulate string data such as converting text to uppercase or lowercase letters.
What is an Argument ?
An argument is a value you pass to a function so the function has data to work with . Function names have parentheses at the end to hold the function arguments. Even if a function has no arguments, the parenthesis are required. Two intrinsic functions include message boxes and input boxes
Selection Structure?
The If Then statement(or only If Statement) is a block of code that will only be run if the specific condition is met and therefor will return True, if the condition returns False the code will jump past the If block and continue at "End If" which is the end of an If block. The syntax for and If statement are:
The If statement check if the condition is True, and here it is. This will make the line(s) inside the If block to be executed. In this example a messagebox will be shown. But if we change "True" to "False" in the above code, the messagebox will not be showed since the code will jump past the If block because the conditions where False.
Dim x As Integer x=3 If x > 0 Then MessageBox.Show("x is greater then 0") End If
The opportunities doesn't end there. We can also create something called an If Then Else statement. This works like an If Then Statement but it has two blocks of codes. If the condition is met(True) the first block of code will be run. But instead of just jumping to the End If straight away if the conditions aren't met(False) the second block of code is executed.
Code: If <condition> Then 'code to be executed if the condition are met Else 'code to be executed if the condition are NOT met End If
Example
Dim x, y, z As Integer x=1 y=9 z = 14 If x < y And y < z Then MessageBox.Show("x is smallest and z is largest") Else MessageBox.Show("The variables are not in size order") End If
The ElseIf blocks is working exactly the same as an If block, the If block is the first one and then it's followed by ElseIf blocks and at the end you can add a else block if you want. If the If block's statement are True that block will be run and then the code will jump to the End If, however if it's False it will test if the condition of the first ElseIf block is True, if this also is False it will go to the second one etc. If all conditions are False and there's an Else block this will be executed.
Here's the syntax for the If Then ElseIf Else Statement: If <condition> Then 'code to be executed if the condition are met ElseIf <condition> Then 'code to be executed if the condition are met but no conditions above Else 'code to be executed if none of the conditions are met End If
Example
Dim x, y, z As Integer x=2 y=5 z=8 If x = 0 Then MessageBox.Show("x is equals to 0") ElseIf x < y And y < z Then MessageBox.Show("x is smallest and z is largest") ElseIf x = y And y = z Then MessageBox.Show("all variables has the same value") Else MessageBox.Show("None of the conditions above are met") End If
Select Statement
The select case statement is good to use when you want different blocks of code to be executed depending on different values on one variable. If statements is good if you only need to test one value Anyway, to use a select case statement you have to create it by writing "Select Case" and then the value you want to test. End the statement with "End Select". Could look something like this:
Example
Select Case myVariable Case 1 MessageBox.Show("myVariable = 1") Case 2 MessageBox.Show("myVariable = 2") Case 3, 4 MessageBox.Show("myVariable = 3 or 4") Case 5 MessageBox.Show("myVariable = 5") Case Else MessageBox.Show("myVariable is nether 1,2,3,4 or 5") End Select
To
When using some sort of values(Integers for example) you can add a whole range of numbers to one case by using "[number] To [number]", like this:
Select Case myVariable Case 0 To 5 MessageBox.Show("myVariable is between 0 and 5") Case 6 To 10 MessageBox.Show("myVariable is between 6 and 10") Case 11 MessageBox.Show("myVariable = 11") End Select
Is
You can also add relational operators to your select case statement. Do this by replace "Case [value]" with "Case Is [relational operator] [value]". Actually a select case statement does always contains a relational operator, the is equals to operator (=) even though it's hidden. This means that "Case Is = myValue" is the same as "Case myValue". Here comes a little example on how to use it:
Looping Structure
The While Loop: The while loop will continue with its loop as long a condition remains True. The condition is tested at the beginning each time the loop will start a new turn. If the condition isn't met at the beginning the loop won't even run once. The syntax of a while loop looks as following: Code: While <condition> 'Code that will be run once per turn End While
Do While loop: This type of loop has only one difference to the While loop more then the syntax. The Do While loop will check the condition at the end instead of in the beginning. This is actually pretty important. Here's the syntax anyway: Do 'Code that will be run once per turn Loop While <condition>
Do Until loop:
The Do While loop will continue if the condition are True and stop if the condition are False. The Do Until loop does the opposite, it will continue if the condition are False and stop if the condition are True. It will loop Until the condition are met. The syntax of the Do Until loop and also an example of it:
Syntax Code: Do 'Code that will be run once per turn Loop Until <condition> Example: Code: Dim X As Integer = 312 Do X /= 10 MessageBox.show(x) Loop Until X = 0
For Loops
The For loop will loop a certain amount of times and when it have looped so many times it will stop. When declaring a For loop you give it a name just like you do when you declares a variable.This is the syntax for declaring a For loop: For <loop_name> As <type> = <start> To <end> 'code inside the loop Next
Ex 02:
For i As Integer = 1 To 10 Step 3 MessageBox.Show(i) Next
MsgBox ( ) Function
A function is similar to a normal procedure but the main purpose of the function is to accept a certain input from the user and return a value which is passed on to the main program to finish the execution. There are two types of functions, the built-in functions.
MsgBox ( ) Function The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he /she can continues. This format is as follows: MsgBox(Prompt, Style Value, Title) The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box,. The Title argument will display the title of the message board.
An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text. The format is
Form Controls
A control is an object that can be drawn on to the Form to enable or enhance user interaction with the application. Examples of these controls, Textboxes, Buttons, Labels, Radio Buttons, etc. All these Windows Controls are based on the Control class, the base class for all controls. Visual Basic allows us to work with controls in two ways: at design time and at runtime. Working with controls at design time means, controls are visible to us and we can work with them by dragging and dropping them from the Toolbox and setting their properties in the properties window. Working at runtime means, controls are not visible while designing, are created and assigned properties in code and are visible only when the application is executed.
Button Event
The default event of the Button is the Click event. When a Button is clicked it responds with the Click Event. The Click event of Button looks like this in code: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click 'You place the code here to perform action when Button is clicked End Sub
TextBox Control
This control looks like a box and accepts input from the user. The TextBox is based on the TextBoxBase class which is based on the Control class. TextBoxes are used to accept input from the user or used to display text. By default we can enter up to 2048 characters in a TextBox but if the Multiline property is set to True we can enter up to 32KB of text. The image below displays a Textbox.
TextBox Event Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As _System.EventArgs) Handles TextBox1.TextChanged End Sub
RichTextBox
RichTextBoxes are similar to TextBoxes but they provide some advanced features over the standard TextBox. RichTextBox allows formatting the text, say adding colors, displaying particular font types and so on.
RichTextBox Event Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged
End Sub
Private Sub Italic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Italic.Click RichTextBox1.SelectionStart = RichTextBox1.Find("are") 'using the Find method to find the text "are" and setting it's 'return property to SelectionStart which selects the text to format Dim ifont As New Font(RichTextBox1.Font, FontStyle.Italic) 'creating a new font object to set the font style RichTextBox1.SelectionFont = ifont 'assigning the value selected from the RichTextBox the font style End Sub Private Sub Font color_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Fontcolor.Click RichTextBox2.SelectionStart = RichTextBox2.Find("are") 'using the Find method to find the text "are" and setting it's return 'property to SelectionStart which selects the text RichTextBox2.SelectionColor = Color.Blue 'setting the color for the selected text with SelectionColor property End Sub Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click RichTextBox3.SaveFile("hello.rtf") 'using SaveFile method to save text in a rich text box to hard disk End Sub Private Sub load_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load.Click RichTextBox4.LoadFile("hello.rtf") 'using LoadFile method to read the saved file End Sub
Label, LinkLabel
Label Labels are those controls that are used to display text in other parts of the application. They are based on the Control class. Notable property of the label control is the text property which is used to set the text for the label.
System.Diagnostics.Process.Start("www.google.com")
'using the start method of system.diagnostics.process class 'process class gives access to local and remote processes End Sub
CheckBox
CheckBoxes are those controls which gives us an option to select, say, Yes/No or True/False. A checkbox is clicked to select and clicked again to deselect some option. When a checkbox is selected a check (a tick mark) appears indicating a selection.
CheckBox Event Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
End Sub
Code to check a CheckBox's state using a button Event Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click If CheckBox1.Checked = True Then TextBox1.Text = "Checked" Else TextBox1.Text = "UnChecked" End If End Sub
RadioButton
RadioButtons are similar to CheckBoxes but RadioButtons are displayed as rounded instead of boxed as with a checkbox. Like CheckBoxes, RadioButtons are used to select and deselect options but they allow us to choose from mutually exclusive options.
RadioButton Event Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
Code to check a RadioButton's state Using a Button Event Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click If RadioButton1.Checked = True Then TextBox1.Text = "Selected" Else TextBox1.Text = "Not Selected" End If End Sub
ListBox
The ListBox control displays a list of items from which we can make a selection. We can select one or more than one of the items from the list.
Button 1
TextBox 4
Button 2
Button 3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = ListBox1.SelectedIndex TextBox2.Text = ListBox1.Items.Count TextBox3.Text = ListBox1.SelectedItem End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click ListBox1.Items.Clear() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ComboBox
ComboBox is a combination of a TextBox and a ListBox. The ComboBox displays an editing field (TextBox) combined with a ListBox allowing us to select from the list or to enter new text. ComboBox displays data in a drop-down style format.
TreeView
The tree view control is used to display a hierarchy of nodes (both parent, child). You can expand and collpase these nodes by clicking them. This control is similar to Windows Explorer which displays a tree view in it's left pane to list all the folders on the hard disk. Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect Label1.Text = e.Node.FullPath End Sub
CheckedListBox As the name says, CheckedListBox is a combination of a ListBox and a CheckBox. It displays a ListBox with a CheckBox towards it's left.
Panel Panels are those controls which contain other controls, for example, a set of radio buttons, checkboxes, etc. Panels are similar to Groupboxes but the difference, Panels cannot display captions where as GroupBoxes can and Panels can have scrollbars where as GroupBoxes can't. If the Panel's Enabled property is set to False then the controls which the Panel contains are also disabled.
GroupBox Control As said above, Groupboxes are used to Group controls. GroupBoxes display a frame around them and also allows to display captions to them which is not possible with the Panel control.
PictureBox Control PictureBoxes are used to display images on them. The images displayed can be anything varying from Bitmap, JPEG, GIF, PNG or any other image format files.
ToolTip, ErrorProvider ToolTip ToolTips are those small windows which display some text when the mouse is over a control giving a hint about what should be done with that control. ToolTip is not a control but a component which means that when we drag a ToolTip from the toolbox onto a form it will be displayed on the component tray.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles MyBase.Load ToolTip1.SetToolTip(TextBox1, "Do not leave this blank") End Sub
ErrorProvider Component
The ErrorProvider component provides an easy way to set validation errors. It allows us to set an error message for any control on the form when the input is not valid. When an error message is set, an icon indicating the error will appear next to the control and the error message is displayed as Tool Tip when the mouse is over the control.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button1.Click If TextBox1.Text = "" Then ErrorProvider1.SetError(TextBox1, "Cannot leave textbox blank") Else ErrorProvider1.SetError(TextBox1, "") End If End Sub
Menus
Menus allow us to make a selection when we want to perform some action with the application, for example, to format the text, open a new file, print and so on. In VB .NET Main Menu is the container for the Menu structure of the form. Menus are made of Menu Item objects that represent individual parts of a menu (like File>New, Open, Save, Save As etc). The two main classes involved in menu handling are, Main Menu and Menu Item. The Main Menu class let's us assign objects to a form's menu class and Menu Item is the class which supports the items in a menu system. Menus like File, Edit, Format etc and the items in those Menus are supported by this Menu Item class. It's this Menu Item's click event that makes these Menus work. For a Menu Item to be displayed, we need to add it to a Main Menu object.
Date Time Picker Date Time Picker allows us to select date and time. Date Time Picker is based on the control class. When we click on the drop-down arrow on this control it displays a month calendar from which we can make selections. When we make a selection that selection appears in the textbox part of the Date Time Picker. The image below displays the Date Time Picker.
Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged TextBox1.Text = DateTimePicker1.Text
End Sub
Month Calendar The Month Calendar control allows us to select date. The difference between a Date Time Picker and Month Calendar is, in Month Calendar we select the date visually and in Date Time Picker when we want to make a selection we click on the drop-down arrow and select the date from the Month Calendar which is displayed. The image below displays a Month Calendar control.
TextBox4.Text =MonthCalendar1.SelectionStart.ToLongDateString
End Sub
The Timer
The Timer control allows you to set a time interval to execute an event after that interval continuously. It is useful when you want to execute certain applications after a certain interval.
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick Label1.Text = TimeOfDay End Sub
Date Formatting
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Label1.Text = Format(Now, "dddd") Label2.Text = Format(Now, "mm") Label3.Text = Format(Now, "yyyy") Label4.Text = System.DateTime.Now.ToString("dd-MMM-yyyy") End Sub
Declaring Variables
Dim str1 As Double Dim str2 As Double Dim calcFunc As String Dim inputStatus As Boolean
Button Event
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If inputStatus = False Then TextBox1.Text += Button1.Text Else TextBox1.Text = Button1.Text inputStatus = False End If
End Sub
Private Sub Clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Clear.Click TextBox1.Text = "" str1 = 0 str2 = 0 calcFunc = " End Sub
Database Access
What is a database? A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. In one view,
Connection - Establishes a connection to a specific data source. Data Provider? A data provider in the .NET Framework serves as a bridge between an application and a data source. A data provider is used to retrieve data from a data source and to resolve changes to that data back to the data source. Data Adapters? Adapters are used to exchange data between a data source and a dataset. A Dataset? Represents a complete set of data including the tables that contain, order, and constrain the data, as well as the relationships between the tables.
Introducing
ADO.NET
ADO.NET is the .NET platforms new database technology, and it builds on ADO (Active Data Objects).
ADO.NET provides DataSet and DataTable objects that are optimized for moving disconnected sets of data across the Internet and intranets, including through firewalls. At the same time, ADO.NET includes the traditional connection and command objects, as well as an object called a DataReader, (which resembles a forward-only, read-only ADO Record Set, in case youre familiar with ADO). Together, these objects provide the best performance and throughput for retrieving data from a database.
ADO.NET architecture
The ADO.NET Data Architecture Data Access in ADO.NET relies on two components: DataSet and Data Provider. DataSet The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in DataSet can be loaded from any valid data source like Microsoft SQL server database, an Oracle database or from a Microsoft Access database. Data Provider The Data Provider is responsible for providing and maintaining the connection to the database. A DataProvider is a set of related components that work together to provide data in an efficient and performance driven manner. The .NET Framework currently comes with two DataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and the OleDb DataProvider which allows us to connect to other types of databases like Access and Oracle. Each DataProvider consists of the following component classes: The Connection object which provides a connection to the database The Command object which is used to execute a command The DataReader object which provides a forward-only, read only, connected recordset The DataAdapter object which populates a disconnected DataSet with data and performs update
Connecting to a Database
To access data in a database, you must first establish a connection using an ADO.NET connection object. Multiple connection objects are included in the .NET Framework, such as the OleDbConnection object (for working with the same OLE DB data providers you would access through traditional ADO) and the SqlConnection object (for optimized access to Microsoft SQL Server).To create an object variable of type OleDbConnection and initialize the variable to a new connection, you could use a statement like this
1. Specify the ConnectionString property of your ADO.NET connection now by placing the following statement in the Load event of your form: <Connection Name>.ConnectionString = _ Provider=Microsoft.Jet.OLEDB.4.0; Data Source=<Database Source> 2. After the connection string is defined, a connection to a data source is established by using the Open () method of the connection object. Add the following statement to the Load event, right after the statement that sets the connection string: <Connection Name>.Open()
Manipulating Data
Understanding DataTables
DataTables contain a snapshot of data in the data source. You generally start by filling a DataTable, manipulating its results, and finally sending the changes back to the data source. The DataTable is populated using the Fill() method of a DataAdapter object, and changes are sent back to the database using the Update() method of a DataAdapter. Any changes made to the DataTable appear only in the local copy of the data until you call the Update method. Having a local copy of the data reduces contention by preventing users from blocking others from reading the data while its being viewed. If youre familiar with ADO, youll note that this is similar to the Optimistic Batch Client Cursor in ADO.
Creating a DataAdapter
To populate a DataTable, you must create a DataAdapter. The DataAdapter youre going to create will use the connection youve already defined to connect to the data source and then execute a query youll provide. The results of that query will be pushed into a DataTable. As mentioned earlier, there are multiple connection objects in the .NET Framework.There are multiple ADO.NET DataAdapter objects as well. Youll be using the OleDbDataAdapter because you will be connecting to Microsoft SQL Server.The constructor for a DataAdapter optionally takes the command to execute when filling a DataTable or DataSet, as well as a connection specifying the data source (you could have multiple connections open in a single project). This constructor has the following syntax:
Dim <Adapter Name> As New OleDb.OleDbDataAdapter ([CommandText],[Connection]);
You must specify the insert, update, and delete statements to use to submit changes from the DataTable to the data source. ADO.NET lets you customize how updates are submitted by enabling you to manually specify these statements as database commands or stored procedures. In this case, youre going to have ADO.NET automatically generate these statements for you by creating a CommandBuilder object. 3. Enter this statement in the class header to create the CommandBuilder variable:
The CommandBuilder is an interesting object in that after you initialize it, you no longer work with it directly: It works behind the scenes to handle the updating, inserting, and deleting of data. To make this work, you have to attach the CommandBuilder to a DataAdapter. You do so by passing a DataAdapter to the CommandBuilder. The CommandBuilder then registers for update events on the DataAdapter and provides the insert, update, and delete commands as needed. 4. Add the following statement to the end of the Form_Load event to initialize the CommandBuilder object: <Command Name> = New OleDb.OleDbCommandBuilder(<Data Adapter Name> )
1. Create the DataTable variable by adding the following statement on the class header to create another variable:
Dim <Data set Name> As New DataTable 2. Youre going to use an integer variable to keep track of the users current position (row) within the DataTable. To do this, add the following statement immediately below the statement you just entered to declare the new DataTable object: Dim < rowPosition variable Name > As Integer = 0
3. You now have a DataAdapter that allows access to a data source via the connection.Youve declared a DataTable that will hold a reference to data. Next add the following statement to the Load event of the form, after the existing code, to fill the DataTable with data: <Data Adapter Name>.Fill(<Dataset Name>)
Search Records.
Dim <Command Name> As New OleDbCommand Dim <Input Variable Name> As String = <Input Filed Name>.Text Try If <Input Variable Name> <> "" Then < Command Name >.CommandText = "SELECT <Filed1,Field2,.> FROM <Table Name> WHERE <Primary Key Field>=" & CInt(<Input Filed Name>.Text ) < Command Name >. Connection = <Connection Name> Dim <Data Reader Name> As OleDbDataReader = < Command Name >.ExecuteReader If <Data Reader Name> .Read = True Then <TextBox Name>.Text = <Data Reader Name> .Item(<Row Index >).ToString <TextBox Name>.Text = <Data Reader Name> .Item(<Row Index >).ToString . <Data Reader Name> . Close() Exit Sub Else <Data Reader Name> .Close() MsgBox("Record not Found: Want to add a Record?") Exit Sub End If End If Catch ex As Exception End Try
Editing Records To edit records in a DataTable, you change the value of a particular column in the desired DataRow. Remember, though, that changes arent made to the original data source until you call Update () on the DataAdapter, passing in the DataTable containing the changes. Youre now going to add a button that the user can click to update the current record. Follow these steps: Double-click the Save button and add the following code to its Click event: If <Dataset name>.Rows.Count <> 0 Then <Dataset name>.Rows(<rowPosition variable Name>)(<Field Name>) = <textbox Name>.Text <Dataset name>.Rows(<rowPosition variable Name>)(<Field Name>) = <textbox Name>.Text .. < Data Adapter Name >.Update(Dataset name) End If
Deleting Records To delete a record from a DataTable, you call the Delete() method on the DataRow to be deleted. Follow these steps: 1. Add a new button to your form (not to the group box) and set its properties as shown in the following table:
2. Double-click the Delete button and add the following code to its Click event: If there is data, delete the current row. If <dataset Name>.Rows.Count <> 0 Then <Dataset name>.Rows(<rowPosition variable Name>).Delete() < Data Adapter Name >.Update(Dataset name) <rowPosition variable Name>= 0 End If
Data Validation
To check weather the entered text is numeric or not we can use is numeric method to ensure data and validate it.
Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus If TextBox1.Text = "" Or IsNumeric(TextBox1.Text) Then ErrorProvider1.SetError(TextBox1, "Cant leave blank or cant be numeric value") TextBox1.Focus() End If End Sub
Error Handling
Try Catch
VB.NET has a inbuilt class that deals with errors. The Class is called Exception. When an exception error is found, an Exception object is created. The coding structure VB.NET uses to deal with such Exceptions is called the Try Catch structure. In the coding area for your button, type the word Try. Then hit the return key on your keyboard. VB.NET completes the rest of the structure for you:
Try rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText) Catch ex As Exception End Try When you run your programme, VB will Try to execute any code in the Try part. If everything goes well, then it skips the Catch part. However, if an error occurs, VB.NET jumps straight to Catch. Add the following to your Catch part: MsgBox(ex.Message) Because ex is an object variable, it now has its own Properties and methods. One of these is the Message property. Run your programme and test it out. Click your button. You should see the following error message:
The one we didn't handle. But the point about this new message box is that it will not crash your programme. You have handled the Exception, and displayed an appropriate message for the user.
If you know the kind of error that a programme might throw, you can get what Type it is from the Error message box you saw earlier. This one:
Click the View Details links under Actions to see the following:
The first line tells us the Type of Exception it is: System.IO.FileNotFoundException You can add this directly to the catch part. Previously, you were just catching any error that might be thrown: Catch ex As Exception But if you know a "file not found" error might be thrown, you can add that to the Catch line, instead of Exception: Catch ex As System.IO.FileNotFoundException You can keep the Exception line as well. (You can have as many Catch parts as you want.) This will Catch any other errors that may occur: Try rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText) Catch ex As System.IO.FileNotFoundException MsgBox(ex.Message) Catch ex As Exception MsgBox(ex.Message) End Try
Crystal Report
How to Creating a Report Using Crystal report in VB.NET? Using Existing Dataset 1. 2. 3. 4. Open the solution Explorer Window. R.Click on the windows application name. Select add >select add new Item. Select Crystal Report from the template list.
5. Select Add button. If the System Popup crystal registration wizard, close that window. Then you will see crystal report gallery
3 4
10
1. 2. 3. 4. 5. 6.
Select Using the Report Expert option.Select OK. Select History from the standard report creation wizard. Click the Browse Button. Select relevant dataset select open button. Select Finish button
7. Select the required table that you wish to add to the report. 8.Select Next. 9.Select the required Fields that you wish to Display on the report. 10.Select Next continuously until get finish button. 11.Select Finish button. 12.The Report Design Window Appears 13.At the left side of the report design view, you will see field Explorer window. 14.If you wish, you can use properties window to change properties of the report..
13
How to Creating a Report Using Crystal report in VB.NET? Using Database file 1. 2. 3. 4. Open the solution Explorer Window. R.Click on the windows application name. Select add >select add new Item. Select Crystal Report from the template list.
5. Select Add button. If the System Popup crystal registration wizard, close that window. Then you will see crystal report gallery
6 3
5 7
10
1. Select Using the Report Expert option.Select OK. 2. Select Database Files from the standard report creation wizard. 3. Click the Browse button & Select relevant database 4. select open button. 5. Select the table that want to be insert 6. Click the add button to add the table
7.Select Next.
8.Select the required Fields that you wish to Display on the report.
9.Select Next continuously until get finish button. 10.Select Finish button. 11.The Report Design Window Appears 12.At the left side of the report design view, you will see field Explorer window. 13.If you wish, you can use properties window to change properties of the report..
12