Академический Документы
Профессиональный Документы
Культура Документы
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.
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.
1. Information hiding,
2. data abstraction,
3. encapsulation,
4. modularity,
5. polymorphism, and inheritance.
Attributes Behaviors
• Skin color • Eat
• Eye color • Bark
• Height • Run
• Weight • Jump
• Etc…. • 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
Data Abstraction and Encapsulation
Abstraction refers to the act of representing essential features without
including the background details or explanations. Classes use the
concept of abstraction and are defined as a list of abstract attributes.
Formula + ingredients+
methods+ etc….
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
(SDLC)
SDLC is the Process of Developing
information system through Investigation,
Analysis, Design, Implementation and
maintenance
The first essential or vital thing required for any software development is system. Also
the system requirement may vary based on the software product that is going to get
developed. So a careful analysis has to be made about the system requirement needed
for the development of the product. After the analysis and design of the system
requirement phase the system required for the development would be complete and the
concentration can be on the software development process.
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.
3. Systems Analysis and Design:
This is an important phase in system development .Here analysis is made on the design of
the system that is going to be developed. In other words database design, the design of the
architecture chosen, functional specification design, low level design documents, high level
design documents and so on takes place. Care must be taken to prepare these design
documents because the next phases namely the development phase is based on these
design documents. If a well structured and analyzed design document is prepared it would
reduce the time taken in the coming steps namely development and testing phases of the
software development life cycle.
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.
System.Windows.Forms
Solution
Explorer
Property
Tool Box
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
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.
Data Types in VB .NET
Data Type Size in Bytes Description
Boolean None
Integer %
Long (Integer) &
Single (Floating) !
Double (Floating) #
Currency @
Date None
Object None
String $
Variant None
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.
1. Procedure level
2. Procedure level, static
3. Form and module level
4. Global level
Within a procedure, variables are declared using the Dim statement:
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:
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:
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:
Just as we can initialize variables in the same line where we declare them, we
can initialize arrays too, with the following constructor:
The number of elements in the curly brackets following the array´s declaration
determines the dimensions of the array, and we can´t add new elements to the
array without resizing it.
Multidimensional Arrays
' 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
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
Operator Use
^ Exponentiation
Negation (used to reverse the sign of the
-
given value, exp -intValue)
* Multiplication
/ Division
\ Integer Division
Mod 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:
Operator Use
+ String Concatenation
& String Concatenation
Example:
str1 = "Concatenation"
str2 = "Operators"
str3 = str1 + str2
MessageBox.Show(str3)
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less 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")
End If
Logical / Bitwise Operators
Operator Use
Not Negation
And Conjunction
AndAlso Conjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction
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:
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 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.
Module Module1
Sub Main()
System.Console.Write("Welcome to Console Applications")
End Sub
End Module
Visual Basic Module and Modules are designed to hold code. All the code
which we write should be within the Module.
Next line starts with Sub Main(), the entry point of the program.
The third line indicates that we are using the Write method of the
System.Console class to write to the console.
Comments in VB.NET begin with a single quote (') character and the
statements following that are ignored by the compiler. Comments are
generally used to specify what is going on in the program and also gives an
idea about the flow of the program. The general form looks like this:
'declaring an integer
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:
If <condition> Then
End If
Example
If True Then
MessageBox.Show("Inside the If block")
End If
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
If Then Else Statement:
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
Else
MessageBox.Show("The variables are not in size order")
End If
If Then ElseIf Else Statement:
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.
If <condition> Then
'code to be executed if the condition are met
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:
End Select
Example
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
More advanced Select Case Statements
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:
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:
Case Is > 0
MessageBox.Show("myVariable is
greater then 0")
Case Is < 0
MessageBox.Show("myVariable is less
then 0")
Case Else
MessageBox.Show("myVariable is
equals to 0")
End Select
Exercise
Part 1 - If statements
Start a new project. Add a textbox, a Label and a button to your new Form. Then write a
programme that does the following:
1. Asks users to enter a number between 10 and 20.
2. The number will be entered into the Textbox.
3. When the Button is clicked, your Visual Basic code will check the number entered in
the Textbox.
4. If it is between 10 and 20, then a message will be displayed.
5. The message box will display the number from the Textbox.
6. If the number entered is not between 10 and 20 then the user will be invited to try
again, and whatever was entered in the Textbox will be erased
Add a Combo box and another button to your form. Create a list of items for your Combo
Box. The list of items in your Combo box can be anything you like - pop groups, football
teams, and favorite foods, anything of your choice. Then try the following:
Use a select case statement to test what a user has chosen from your drop-down list.
Give the user a suitable message when the button was clicked.
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
Dim X as Integer = 3
While X<300
X*=2
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>
Example
Dim x As Integer
x = 10
Do
MessageBox.Show(x)
x+=1
Loop While x < 15
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:
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:
Ex 01:
For i As Integer = 0 To 2
MessageBox.Show(i)
Next
Ex 02:
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:
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.
The InputBox( ) Function
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
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:
'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
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
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
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")
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
End Sub
Code to check a CheckBox's state using a button Event
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
End Sub
Code to check a RadioButton's state Using a Button Event
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.
TextBox 1
TextBox 2
TextBox 3
Button 1 Button 3
TextBox 4 Button 2
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
ListBox1.Items.Clear()
End Sub
ListBox1.Items.RemoveAt(TextBox5.Text)
End Sub
ComboBox
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.
Label1.Text = e.Node.FullPath
End Sub
1
CheckedListBox
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.
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.
End Sub
Menus
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.
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.
Label1.Text = TimeOfDay
End Sub
Date Formatting
End Sub
Creating a Simple Calculator
Declaring Variables
str2 = TextBox1.Text
Select Case calcFunc
Case "+"
str1 = str1 + str2
Case "-"
str1 = str1 - str2
Case "/"
str1 = str1 / str2
Case "*"
str1 = str1 * str2
End Select
TextBox1.Text = str1
inputStatus = True
End Sub
Button Event
End Sub
TextBox1.Text = ""
str1 = 0
str2 = 0
calcFunc = "“
End Sub
CalculateTotals()
calcFunc = "“
End If
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,
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 platform’s 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 you’re familiar with ADO).
Data Access in ADO.NET relies on two components: DataSet and Data Provider.
DataSet
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:
<Connection Name>.ConnectionString = _
“Provider=Microsoft.Jet.OLEDB.4.0; Data Source=<Database 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
it’s being viewed.
If you’re familiar with ADO, you’ll 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 you’re
going to create will use the connection you’ve already defined to connect to the data
source and then execute a query you’ll 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. You’ll 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).
1. Add the following statement immediately below the statement you entered to declare the <Connection
Name> object (in the class header, not in the Load event) to create a variable:
2. Add the following statement at the bottom of the Load event of the form (immediately following the
statement that opens the 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, you‟re 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:
1. Create the DataTable variable by adding the following statement on the class header to
create another variable:
2. You’re going to use an integer variable to keep track of the user’s 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:
3. You now have a DataAdapter that allows access to a data source via the
connection.You’ve 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:
Try
If <Input Variable Name> <> "" Then
Exit Sub
End If
End If
Catch ex As Exception
End Try
Add, Edit, Delete, Update
Records.
Creating New Records
Adding records to a DataTable is performed much like editing records. However, to create a
new row in the DataTable, you must first call the NewRow() method. After creating the new
row, you can set its column values. Follow these steps:
To edit records in a DataTable, you change the value of a particular column in the desired
DataRow. Remember, though, that changes aren‟t made to the original data source until you
call Update () on the DataAdapter, passing in the DataTable containing the changes. You‟re
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:
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:
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.
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
Catch ex As Exception
End Try
The Try word means "Try to execute this code". The Catch word means "Catch
any errors here". The ex is a variable, and the type of variable it is is an Exception
object.
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:
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
Try … Catch ….Finally:
Try
Catch ex As Exception
Finally
End Try
The Finally part is always executed, whether an error occurs or not. You typically add a Finally
part to perform any cleanup operations that are needed. For example, you may have opened
a file before going into a Try … Catch Statement. If an error occurs, the file will still be open.
Whether an error occurs or not, you still need to close the file. You can do that in the Finally
part.
Crystal Report
How to Creating a Report Using Crystal report in VB.NET?
6 5
7 9
8 10
8.Select” Next”.
13.At the left side of the report design view, you will
13
see “field Explorer” window.
4 5
7
8
9 10
12.At the left side of the report design view, you will
see “field Explorer” window.
12
13.If you wish, you can use properties window to
change properties of the report..
Viewing the Crystal Report
How to display the Report (How to view data)