Professional Documents
Culture Documents
8/16/2011
.NET Defined
Before getting deeply into the subject we will first know how Businesses are related to Internet, what .NET means to them and what exactly .NET is built upon. As per the product documentation from a Business perspective, there are three phases of the Internet. The First phase gets back to the early 1990's when Internet first came into general use and which brought a big revolution for Businesses. In the First phase of the Internet Businesses designed and launched their Website's and focused on the number of hits to know how many customers were visiting their site and interested in their products, etc. The Second phase is what we are in right now and in this phase Businesses are generating revenue through Online Transactions. We are now moving into the Third phase of the Internet where profit is the main priority. The focus here is to Businesses effectively communicate with their customers and partners who are geographically isolated, participate in Digital Economy and deliver a wide range of services. How can that be possible? The answer, with .NET.
8/16/2011
What is .NET ?
Many people reckon that it's Microsoft's way of controlling the Internet, which is false. .NET is Microsoft's strategy of software that provides services to people any time, any place, on any device. An accurate definition of .NET is, it's an XML Web Services platform which allows us to build rich .NET applications, which allows users to interact with the Internet using wide range of smart devices (tablet devices, pocket PC's, web phones etc), which allows to build and integrate Web Services and which comes with many rich set of tools like Visual Studio to fully develop and build those applications.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 3
EDITIONS OF VB .NET
Academic Edition Professional Edition Enterprise Developer Edition Enterprise Architect Edition
8/16/2011
Types Of Projects
Windows Applications Class Libraries Windows Control Libraries Smart Device Applications Asp .Net Web Applications Asp .Net Web Services Asp .Net Mobile Web Application Web Control Library Consol Application Windows Services
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi
8/16/2011
.Suo
.Xsd .Htm .Txt .Xslt .Css .Rpt .Bmp .Js .Vbs .Wsf .Aspx .Asp
An Xml Schema Provided To Create Datasets An Html Document A Text File An Xslt Stylesheet File Cascaded Stylesheet Crystal Report Bitmap File Jscript File Vbscript File Windows Scripting File A Web Form An Active Server Page
8/16/2011
.Asmx Web Service Class .Vsdisco A Dynamic Discovery Project .Web A We Configuration File .Asax A Global Application Class .Rex A Resource File To Store Resource Information .Sln Solution File .Vbproj Vb Project File .Vbproj.User Vb Project User Option File
8/16/2011
Start Page Menu Bar Toolbars New Project Dilogbox Object Browser The Toolbox The Solution Explorer Class View Window Property Window Dynamic Help Window Component Tray The Server Explorer
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 10
8/16/2011
The Output Window The Task List The Command Window Graphical Designers Form Designers Web Form Designers Component Designer Xml Designeres Code Designers
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 11
8/16/2011
MODES OF VB .NET
Design Time Mode Runtime Mode Break Time Mode
8/16/2011
12
VB Language
Visual Basic, the name makes me feel that it is something special. In the History of Computing world no other product sold more copies than Visual Basic did. Such is the importance of that language which clearly states how widely it is used for developing applications. Visual Basic is very popular for it's friendly working (graphical) environment. Visual Basic. NET is an extension of Visual Basic programming language with many new features in it. The changes from VB to VB .NET are huge, ranging from the change in syntax of the language to the types of projects we can create now and the way we design applications. Visual Basic .NET was designed to take advantage of the .NET Framework base classes and runtime environment. It comes with power packed features that simplify application development.
8/16/2011
13
Namespaces
A namespace is a collection of different classes. All VB applications are developed using classes from the .NET System namespace. The namespace with all the built-in VB functionality is the System namespace. All other namespaces are based on this System namespace
8/16/2011
14
System: Includes essential classes and base classes for commonly used data types, events, exceptions and so on System. Collections: Includes classes and interfaces that define various collection of objects such as list, queues, hash tables, arrays, etc System. Data: Includes classes which lets us handle data from data sources System.Data.OleDb: Includes classes that support the OLEDB .NET provider
8/16/2011
15
methods Files
System.IO: Includes classes for data access with System. Threading: Includes classes and interfaces
to support multithreaded System. Web: Includes classes and interfaces that support browser-server System.Windows.Forms: Includes classes for creating Windows based forms
8/16/2011
16
Assemblies
An assembly is the building block of a .NET
application. It is a self describing collection of code, resources, and metadata (data about data, example, name, size, version of a file is metadata about that file). An Assembly is a complied and versioned collection of code and metadata that forms an atomic functional unit.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 17
library (.dll) file or executable program file (.exe) Assemblies are made of two parts: manifest, contains information about what is contained within the assembly and modules internal files of IL code which are ready to run The assembly file is visible in the Solution Explorer window of the project.
8/16/2011
18
DataTypes
Data Type Byte Char Integer Double Long Short Size in Bytes 1 8-bit 2 16-bit 4 32-bit 8 64-bit 8 64-bit 2 16-bit System.Byte System.Char System.Int32 System.Double System.Int64 System.Int16
8/16/2011
19
Contd..
Single String Date Boolean Object Decimal 4 32-bit System.Single Varies Non-Numeric System.String 8 System.Date 2 Non-Numeric System.Boolean 4 Non-Numeric System.Object 16 128-bit System.Decimal
8/16/2011
20
Access Specifiers
1. Public: Gives variable public access which
means that they are accessible only within their declaration content Protected: Protected access gives a variable accessibility within their own class or a class derived from that class
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 21
Friend: Gives variable friend access which means that they are
access
Static: Makes a variable static which means that the variable will
hold the value even the procedure in which they are declared ends
Shared: Declares a variable that can be shared across many
instances and which is not associated with a specific instance of a class or structure
8/16/2011
22
Variables
Variables are used to store data. A variable has a name to which we refer and the data type, the type of data the variable holds. VB .NET now needs variables to be declared before using them. Variables are declared with the Dim keyword. Dim stands for Dimension.
8/16/2011
23
Example of variable
Dim a,b,c as Integer
'declaring three variables of type integer a=10 b=20 c=a+b Write("Sum of a and b is" & c) End Sub
8/16/2011
24
Statements
A statement is a complete instruction. It can contain keywords, operators, variables, literals, expressions and constants. Each statement in Visual Basic should be either a declaration statement or a executable statement. A declaration statement is a statement that can create a variable, constant, data type. They are the one's we generally use to declare our variables. On the other hand, executable statements are the statements that perform an action. They execute a series of statements. They can execute a function, method, loop, etc.
8/16/2011
25
Option Statement
The Option statement is used to set a number
of options for the code to prevent syntax and logical errors. This statement is normally the first line of the code. The Option values in Visual Basic are as follows. Option Compare: You can set it's value to Text or Binary. This specifies if the strings are compared using binary or text comparison operators.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 26
Contd
Option Explicit: Default is On. You can set it
to Off as well. This requires to declare all the variables before they are used. Option Strict: Default is Off. You can set it to On as well. Used normally when working with conversions in code. If you want to assign a value of one type to another then you should set it to On and use the conversion functions else Visual Basic will consider that as an error.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 27
Explicit Conversions
When types cannot be implicitly converted you should convert them explicitly. This conversion is also called as cast. Explicit conversions are accomplished using CType function. CType function for conversion If we are not sure of the name of a particular conversion function then we can use the CType function. The above example with a CType function looks like this: Imports System.Console Module Module1 Sub Main() Dim d As Double d = 132.31223 Dim i As Integer i = CType(d, i) 'two arguments, type we are converting from, to type desired WriteLine("Integer value is" & i) End Sub End Module
8/16/2011
28
Explicit Conversions
CBool - use this function to convert to Bool data type CByte - use this function to convert to Byte data type CChar - use this function to convert to Char data type CDate - use this function to convert to Date type CDbl - use this function to convert to Double data type CDec - use this function to convert to Decimal data type CInt - use this function to convert to Integer data type CLng - use this function to convert to Long data type CObj - use this function to convert to Object type CShort - use this function to convert to Short data type CSng - use this function to convert to Single data type CString - use this function to convert to String data type
8/16/2011
29
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 and they are described below in the order of their precedence
8/16/2011
30
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 \ Integer Division Mod Modulus Arithmetic + Addition Subtraction
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 31
8/16/2011
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
8/16/2011
32
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: Operator Use = Equality <> Inequality < Less than > Greater than >= Greater than or equal to <= Less than or equal to
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 33
8/16/2011
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: Operator Use Not Negation And Conjunction AndAlso Conjunction Or Disjunction OrElse Disjunction Xor Disjunction
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 34
8/16/2011
Arrays
Arrays are programming constructs that store data and allow us to access them by numeric index or subscript. Arrays helps us create shorter and simpler code in many situations. Arrays in Visual Basic .NET inherit from the Array class in the System namespace. All arrays in VB as zero based, meaning, the index of the first element is zero and they are numbered sequentially. You must specify the number of array elements by indicating the upper bound of the array. The upper bound is the numder that specifies the index of the last element of the array. Arrays are declared using Dim, ReDim, Static, Private, Public and Protected keywords. An array can have one dimension (liinear arrays) or more than one (multidimensional arrays). The dimensionality of an array refers to the number of subscripts used to identify an individual element. In Visual Basic we can specify up to 32 dimensions. Arrays do not have fixed size in Visual Basic.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 35
8/16/2011
36
Array Declaration
To declare a single-dimensional array variable In your declaration, add one pair of parentheses after the variable name, as in the following example: Dim MySingleArray() As Integer To declare a multidimensional array variable In your declaration, add one pair of parentheses after the variable name and place commas inside the parentheses to separate the dimensions, as in the following example: Dim My4DArray(,,,) As Short ' Four-dimensional array. To declare a jagged array variable In your declaration, add as many pairs of parentheses after the variable name as there are levels of nested arrays, as in the following example: Dim MyJaggedArray()()() As Byte ' Array of arrays of Byte arrays.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 37
Initializing Arrays
Specify the initial length of one or more of the
dimensions in the parentheses following the variable name, without assigning an array object to the variable. Assign an array object to the variable, using the New clause. When you use a New clause, you must follow it with braces ({}), even if they are empty. Assign an array object to the variable and supply initial lengths in the New clause. Assign an array object to the variable and supply initial element values in the New clause. You can supply both lengths and values in the same New clause.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 38
specified). Dim A() As Byte = New Byte() {} ' Empty Byte array object. Dim A() As Byte = New Byte() ' INVALID (missing braces). Dim A() As Byte = New Byte(2) ' INVALID (missing braces). Dim A() As Byte = New Byte() {0,1,2} ' (0) through (2). Dim BA() As Byte = New Byte(2) {0,1,2} ' (0) through (2).
8/16/2011
39
Resizing Arrays
array object to the same array variable, using either ReDim . The new array object can have different dimensions, although it must retain the same rank. For example, you can use a large array for a short time and then ReDim it to a smaller size. This frees up memory you no longer need. When you ReDim an array, its existing values are normally lost. However, you can retain them by including the Preserve keyword in the ReDim statement. For example, the following statement allocates a new array, ReDim Preserve MyArray(10, 20) In a multidimensional array, you can change only the last dimension when you use Preserve. If you attempt to change any of the other dimensions, a run-time error occurs. If you do not know the current size of a dimension, you can use the GetUpperBound method, which returns the highest subscript value for the dimension you specify.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 40
CONTROL STATEMENTS
IF condition THEN ELSEIF condition THEN ELSE END IF SELECT CASE expr CASE exprlst1 CASE exprlst2 . . CASE exprlstN END SELECT SWITCH(expr-1,value-1,expr-2, value-2,..expr-N, value-N) CHOOSE(index,chice-1, chice-2, chice-3. chice-N)
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 41
LOOPING CONSTUCTS
DO while/until condition
Stmt Exit do LOOP for index=start to end step Statements Exit for NEXT WHILE condition Statements WEND WITH object Statements END WITH
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 42
8/16/2011
43
Sub procedures
A Sub procedure is a series of Visual Basic
statements enclosed by the Sub and End Sub statements. Each time the procedure is called, its statements are executed, starting with the first executable statement after the Sub statement and ending with the first End Sub, Exit Sub, or Return statement encountered. A Sub procedure performs actions but does not return a value. It can take arguments, such as constants, variables, or expressions, that are passed to it by the calling code.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 44
Contd
The syntax for declaring a Sub procedure is as follows: [accessibility] Sub subname[(argumentlist)] ' Statements of the Sub procedure go here. End Sub The accessibility can be Public, Protected, Friend, Protected Friend, or Private. You can define Sub procedures in modules, classes, and structures. They are Public by default, which means you can call them from anywhere in your application.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 45
Argument Declaration
You declare each argument for a procedure the same
way you declare a variable, specifying the argument name and data type. You can also specify the passing mechanism, and whether the argument is optional. The syntax for each argument in the argument list is as follows: [Optional] [ByVal|ByRef] [ParamArray] argumentname As datatype If the argument is optional, you must also supply a default value in its declaration, as follows: Optional [ByVal|ByRef] argumentname As datatype = defaultvalue
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi
46
Calling Syntax
You invoke a Sub procedure explicitly with a stand-
alone calling statement. You cannot call it by using its name within an expression. The calling statement must provide values for all arguments that are not optional, and it must enclose the argument list in parentheses. If no arguments are supplied, you can optionally omit the parentheses. The use of the Call keyword is optional also. The syntax for a call to a Sub procedure is as follows: [Call] subname[(argumentlist)]
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 47
8/16/2011
Example of sub
Sub sumofnos(ByVal a as intege,b as integer) Dim c as integer C= a+b MessageBox.Show(sum of" & a & " and " & b & is &c) End Sub Call this procedure as Call sumofnos(10,20)
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 48
Projects are composed of files, which are compiled into applications. When you start a project and open the code editor, you see some code already in place and in the correct order. Any code that you write should follow this sequence: Option statements Imports statements The Main procedure Class, Module, and Namespace, if applicable, statements
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 49
8/16/2011
Function Procedures
A Function procedure is a series of Visual Basic
statements enclosed by the Function and End Function statements. Each time the procedure is called, its statements are executed, starting with the first executable statement after the Function statement and ending with the first End Function, Exit Function, or Return statement encountered. A Function procedure is similar to a Sub procedure, but it also returns a value to the calling program. A Function procedure can take arguments passed to it by the calling code, such as constants, variables, or expressions.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 50
Contd
The syntax for declaring a Function
procedure is as follows: [accessibility] Function functionname[(argumentlist)] As datatype ' Statements of the Function procedure. End Function The accessibility can be Public, Protected, Friend, Protected Friend, or Private.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 51
example
New Return statement Can still set function name to value Better to use the Return statement
Private Function CalculateSum( _ ByVal intNum1 As Integer, _ ByVal intNum2 As Integer) As Integer Return intNum1 + intNum2 End Function Calling the function C=calculatesum(10,20)
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 52
Menus
Create a menu by
adding a MainMenu control to the component tray Great new Menu Designer replaces the Menu Editor
8/16/2011
53
Menus
For Context menus, add a ContextMenu
control A ContextMenu uses the same Menu Designer as a MainMenu Attach a context menu by setting the ContextMenu property of a control or the form
8/16/2011
54
Messagebox Function
1. MessageBox.Show(Arguments) Several choices for argument list
Introduces concept of Overloaded functions Multiple signatures to choose from MessageBox.Show(TextMessage) MessageBox.Show(TextMessage, TitlebarText) MessageBox.Show(TextMessage, TitlebarText, _ MessageBoxButtons) MessageBox.Show(TextMessage, TitlebarText, _ MessageBoxButtons, MessageBoxIcon)
8/16/2011
55
Messagebox Function
MessageBox Icons and buttons
Enumeration of constants
8/16/2011
56
Button Control
One of the most popular control in Visual
Basic is the Button Control (previously Command Control). They are the controls which we click and release to perform some action. Buttons are used mostly for handling events in code, say, for sending data entered in the form to the database and so on. The default event of the Button is the Click event and the Button class is based on the ButtonBase class which is based on the Control class.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 57
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
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 58
background color and a background image to the button. We set the font color and font style for the text that appears on button with ForeColor and the Font property. We change the appearance style of the button with the FlatStyle property. We can change the text that appears on button with the Text property with the TextAlign property we can set where on the button the text should appear from a predefined set of options.
8/16/2011
59
Enabled and Visible properties. The Enabled property is set to True by default which makes the button enabled and setting it's property to False makes the button Disabled. With the Visible property we can make the Button Visible or Invisible. The default value is set to True and to make the button Invisible set it's property to False.
8/16/2011
60
Layout Layout properties are about the look of the Button. Note the
Dock property here. A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container. The default value is set to none. If you want to dock the control towards the left, right, top, bottom and center you can do that by selecting from the button like image this property displays. With the Location property you can change the location of the button. With the Size property you can set the size of the button. Apart from the Dock property you can set it's size and location by moving and stretching the Button on the form itself.
8/16/2011
61
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles_ MyBase.Load Dim Button1 as New Button() 'declaring the button, Button1 Button1.Text="Creating a Button" 'setting the text to be displayed on the Button Button1.Location=New Point(100,50) 'setting the location for the Button where it should be created Button1.Size=New Size(75,23) 'setting the size of the Button Me.Controls.Add(Button1) 'adding the Button that is created to the form 'the Me keyword is used to refer to the current object, in this case the Form End Sub End Class
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 62
8/16/2011
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.
8/16/2011
63
System.Object, ByVal e As System.EventArgs)_ Handles MyBase.Load Dim Label1 As New Label() Label1.Text = "Label" Label1.Location = New Point(135, 70) Label1.Size = New Size(30, 30) Me.Controls.Add(Label1) End Sub
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 64
TextBox Control
Windows users should be familiar with textboxes.
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
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 65
property to False. Multiline: Setting this property to True makes the TextBox multiline which allows to accept multiple lines of text. Default value is False. PasswordChar: Used to set the password character. The text displayed in the TextBox will be the character set by the user. Say, if you enter *, the text that is entered in the TextBox is displayed as *. ReadOnly: Makes this TextBox readonly. It doesn't allow to enter any text. Visible: Default value is True. To hide it set the property to False
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 66
possible options. The default value is left and you can set the alignment of text to right or center. Scrollbars: Allows to add a scrollbar to a Textbox. Very useful when the TextBox is multiline. You have four options with this property. Options are are None, Horizontal, Vertical and Both. Depending on the size of the TextBox anyone of those can be used.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 67
numbers which can restrict accidental operations. For example, adding two numbers of the form 27+2J cannot return anything. To avoid such kind of operations we use the KeyPress event of the TextBox.
Code that allows you to enter only double digits in a TextBox looks like this: Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As_ System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress If(e.KeyChar < "10" Or e.KeyChar > "100") Then MessageBox.Show("Enter Double Digits") End If End Sub
8/16/2011
68
System.Windows.Forms.Form Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MyBase.Load Dim TextBox1 as New TextBox() TextBox1.Text="Hello Mate" TextBox1.Location=New Point(100,50) TextBox1.Size=New Size(75,23) Me.Controls.Add(TextBox1) End Sub End Class
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 69
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. The CheckBox control is based on the TextBoxBase class which is based on the Control class. Below is the image of a Checkbox.
8/16/2011
70
Notable Properties
Important properties of the CheckBox in the Appearance section
of the properties window are: Appearance: Default value is Normal. Set the value to Button if you want the CheckBox to be displayed as a Button. BackgroundImage: Used to set a background image for the checkbox. CheckAlign: Used to set the alignment for the CheckBox from a predefined list. Checked: Default value is False, set it to True if you want the CheckBox to be displayed as checked. CheckState: Default value is Unchecked. Set it to True if you want a check to appear. When set to Indeterminate it displays a check in gray background. FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of the checkbox.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 71
CheckBox
Important property in the Behavior section of
the properties window is the ThreeState property which is set to False by default. Set it to True to specify if the Checkbox can allow three check states than two.
8/16/2011
72
CheckBox
Code to check a CheckBox's state 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
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 73
CheckBox
Creating a CheckBox in Code Private Sub Form1_Load(ByVal sender As
System.Object, ByVal e As_ System.EventArgs) Handles_ MyBase.Load Dim CheckBox1 As New CheckBox() CheckBox1.Text = "Checkbox1" CheckBox1.Location = New Point(100, 50) CheckBox1.Size = New Size(95, 45) Me.Controls.Add(CheckBox1) End Sub
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 74
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 dropdown style format. The ComboBox class is derived from the ListBox class. Below is the Image of a ComboBox.
8/16/2011
75
properties window allows us to set the look of the ComboBox. The default value is set to DropDown which means that the ComboBox displays the Text set by it's Text property in the Textbox and displays it's items in the DropDownListBox below. Setting it to simple makes the ComboBox to be displayed with a TextBox and the list box which doesn't drop down. Setting it to DropDownList makes the ComboBox to make selection only from the drop down list and restricts you from entering any text in the textbox. We can sort the ComboBox with it's Sorted property which is set to False by Default. We can add items to the ComboBox with it's Items property.
8/16/2011
76
Removing items from a ComboBox You can remove all items or one particular
item from the list box part of the ComboxBox. Code to remove a particular item by it's Index number looks like this: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click ComboBox1.Items.RemoveAt(4) 'removing an item by specifying it's index End Sub
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 77
Code to remove all items from the ComboBox Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click ComboBox1.Items.Clear() 'using the clear method to clear the list box End Sub
8/16/2011
78
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. The ListBox control is based on the ListControl class which is based on the Control class. The image below displays a ListBox.
8/16/2011
79
ListBox. Works when the ListBox has MultipleColumns. MultiColumn: The default value is set to False. Set it to True if you want the list box to display multiple columns. ScrollAlwaysVisible: Default value is set to False. Setting it to True will display both Vertical and Horizontal scrollbar always. SelectionMode: Default value is set to one. Select option None if you do not any item to be selected. Select it to MultiSimple if you want multiple items to be selected. Setting it to MultiExtended allows you to select multiple items with the help of Shift, Control and arrow keys on the keyboard. Sorted: Default value is set to False. Set it to True if you want the items displayed in the ListBox to be sorted by alphabetical order.
8/16/2011
80
Counting the number of Items in a ListBox Add a Button to the form and place the following code in it's click
event. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles Button1.Click TextBox1.Text = ListBox1.Items.Count 'counting the number of items in the ListBox with the Items.Count End Sub When you run the code and click the Button it will display the number of items available in the ListBox. Code to display the item selected from ListBox in a TextBox Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged TextBox1.Text = ListBox1.SelectedItem 'using the selected item property End Sub When you run the code and click an item in the
8/16/2011
81
System.Object, ByVal e _ As System.EventArgs) Handles Button1.Click ListBox1.Items.RemoveAt(4) 'removing an item by specifying it's index End Sub Code to Remove all items Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ListBox1.Items.Clear() 'using the clear method to clear the list box End Sub
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 82
Example
8/16/2011
83
Code to Shift single selected item from one listbox to another listbox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ListBox1.Items.Add(ListBox2.Items.Item(ListBox2.SelectedIndex)) ListBox2.Items.RemoveAt(ListBox2.SelectedIndex) End Sub
8/16/2011
85
8/16/2011
86
8/16/2011
87
Private Sub CheckBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.Click, CheckBox2.Click, CheckBox3.Click If flag = True Then If CheckBox1.Checked = True Then TextBox1.ForeColor = Color.Red ElseIf CheckBox2.Checked = True Then TextBox1.ForeColor = Color.Green ElseIf CheckBox3.Checked = True Then TextBox1.ForeColor = Color.Yellow End If Else If CheckBox1.Checked = True Then TextBox1.BackColor = Color.Red ElseIf CheckBox2.Checked = True Then TextBox1.BackColor = Color.Green ElseIf CheckBox3.Checked = True Then TextBox1.BackColor = Color.Yellow NAVGUJARAT COLLEGE OF COMPUTER 88 8/16/2011 End If End If APPLICATIONS Kaushar Ghanchi End Sub
Example-Calculator
8/16/2011
89
8/16/2011
90
8/16/2011
91
8/16/2011
92
We can handle mouse events such as mouse pointer movements in Forms. The mouse events supported by VB .NET are as follows: MouseDown: This event happens when the mouse pointer is over the form/control and is pressed MouseEnter: This event happens when the mouse pointer enters the form/control MouseUp: This event happens when the mouse pointer is over the form/control and the mouse button is released MouseLeave: This event happens when the mouse pointer leaves the form/control MouseMove: This event happens when the mouse pointer is moved over the form/control MouseWheel: This event happens when the mouse wheel moves while the form/control has focus MouseHover: This event happens when the mouse pointer hovers over the form/control The properties of the MouseEventArgs objects that can be passed to the mouse event handler are as follows: Button: Specifies that the mouse button was pressed Clicks: Specifies number of times the mouse button is pressed and released X: The X-coordinate of the mouse click Y: The Y-coordinate of the mouse click Delta: Specifies a count of the number of detents (rotation of mouse wheel) the mouse wheel has rotated
8/16/2011
93
Common Dialogs
Visual Basic .NET comes with built-in dialog boxes which allow us to create our own File Open, File Save, Font, Color dialogs much like what we see in all other windows applications. To make a dialog box visible at run time we use the dialog box's ShowDialog method. The Dialog Boxes which come with Visual Basic .NET are: OpenFileDialog, SaveFileDialog FontDialog ColorDialog PrintDialog PrintPreviewDialog and PageSetupDialog. We will be working with OpenFile, SaveFile, Font and Color Dialog's in this section. The return values of all the above said dialog boxes which will determine which selection a user makes are: Abort, Cancel, Ignore, No, None, OK, Return, Retry and Yes.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 94
OpenFileDialog
Properties of the OpenFileDialog are as follows: AddExtension: Gets/Sets if the dialog box adds extension to file names if the user doesn't supply the extension. CheckFileEixsts: Checks whether the specified file exists before returning from the dialog. CheckPathExists: Checks whether the specified path exists before returning from the dialog. DefaultExt: Allows you to set the default file extension. FileName: Gets/Sets file name selected in the file dialog box. FileNames: Gets the file names of all selected files. Filter: Gets/Sets the current file name filter string, which sets the choices that appear in the "Files of Type" box. FilterIndex: Gets/Sets the index of the filter selected in the file dialog box. InitialDirectory: This property allows to set the initial directory which should open when you use the OpenFileDialog.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 95
MultiSelect: This property when set to True allows to select multiple file extensions. ReadOnlyChecked: Gets/Sets whether the read-only checkbox is checked. RestoreDirectory: If True, this property restores the original directory before closing. ShowHelp: Gets/Sets whether the help button should be displayed. ShowReadOnly: Gets/Sets whether the dialog displays a read-only check box. Title: This property allows to set a title for the file dialog box. ValidateNames: This property is used to specify whether the dialog box accepts only valid file names.
8/16/2011
96
SaveFileDialog
Save File Dialog's are supported by the SaveFileDialog class and they allow us to save the file in a specified location. Properties of the Save File Dialog are the same as that of the Open File Dialog. Please refer above. Notable property of Save File dialog is the OverwritePromopt property which displays a warning if we choose to save to a name that already exists.
8/16/2011
97
FontDialog
Properties of the FontDialog are as follows: AllowSimulations: Gets/Sets whether the dialog box allows graphics device interface font simulations. Color: Gets/Sets selected font color. Font: Gets/Sets the selected font. FontMustExist: Gets/Sets whether the dialog box specifies an error condition if the user attempts to select a font or size that doesn't exist. MaxSize: Gets/Sets the maximum point size the user can select. MinSize: Gets/Sets the mainimum point size the user can select. ShowApply: Gets/Sets whether the dialog box contains an apply button. ShowColors: Gets/Sets whether the dialog box displays the color choice. ShowEffects: Gets/Sets whether the dialog box contains controls that allow the user to specify to specify strikethrough, underline and text color options. ShowHelp: Gets/Sets whether the dialog box displays a help button.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 98
ColorDialogs
Properties of ColorDialog are as follows: AllowFullOpen: Gets/Sets whether the user can use the dialog box to define custom colors. AnyColor: Gets/Sets whether the dialog box displays all the available colors in the set of basic colons. Color: Gets/Sets the color selected by the user. CustomColors: Gets/Sets the set of custom colors shown in the dialog box. FullOpen: Gets/Sets whether the controls used to create custom colors are visible when the dialog box is opened. ShowHelp: Gets/Sets whether the dialog box displays a help button. SolidColorOnly: Gets/Sets whether the dialog box will restrict users to selecting solid colors only.
8/16/2011
99
TREEVIEW CONTROL
The Windows Forms TreeView control displays a hierarchy of nodes, like the way files and folders are displayed in the left pane of Windows Explorer. Each node might contain other nodes, called child nodes. Parent nodes, or nodes that contain child nodes, can be displayed as expanded or collapsed. A tree view can also be displayed with check boxes next to the nodes, if the tree view's CheckBoxes property is set to true. You can then programmatically select or clear nodes by setting the node's Checked property to true or false.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 100
TREEVIEW PROPERTIES
1. NODES-contains the list of top-level nodes
in the tree view 2. SELECTEDNODES-sets the currently selected node 3. ImageList -Icons can be displayed next to the nodes; the images are taken from the ImageList control
8/16/2011
101
TREEVIEW-ADDING NODES
To add or remove nodes in the designer 1. Select the TreeView control or add one to the form. 2. In the Properties window, click the ellipsis () button next to the Nodes property. 3. The TreeNode Editor appears. 4. To add nodes, a root node must exist; if one does not exist, you must first add a root by clicking the Add Root button. You can then add child nodes by selecting the root or any other node and clicking the Add Child button. To delete nodes, select the node to delete and then click the Delete button.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 102
To add nodes programmatically Use the Add method of the tree view's Nodes property. Dim newNode As TreeNode = New TreeNode("Text for new node") TreeView1.SelectedNode.Nodes.Add(newNode )
8/16/2011
103
To remove nodes programmatically Use the Remove method of the tree view's Nodes property to remove a single node, or the Clear method to clear all nodes. TreeView1.Nodes.Remove(TreeView1.Selected Node) nodes.TreeView1.Nodes.Clear()
8/16/2011
104
Listview Control
The Windows Forms ListView control displays a list of items with icons. You can use a list view to create a user interface like the right pane of Windows Explorer The control has four view modes: LargeIcon, SmallIcon, List, and Details. The LargeIcon mode displays large icons next to the item text; the items appear in multiple columns if the control is large enough. The SmallIcon mode is the same except that it displays small icons. The List mode displays small icons but is always in a single column. The Details mode displays items in multiple columns.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 105
contains the items displayed by the control. The SelectedItems property contains a collection of the items currently selected in the control. The user can select multiple items, for example to drag and drop several items at a time to another control, if the MultiSelect property is set to true. The ListView control can display check boxes next to the items, if the CheckBoxes property is set to true. The Activation property determines what type of action the user must take to activate an item in the list: the options are Standard, OneClick, and TwoClick. OneClick activation requires a single click to activate the item. TwoClick activation requires the user to double-click to activate the item; a single click changes the color of the item text. Standard activation requires the user to double-click to activate an item, but the item does not change appearance
8/16/2011
106
In the Properties window, click the ellipsis button () next to the Items property. The ListViewItem Collection Editor appears. To add an item, click the Add button. You can then set properties of the new item, such as the Text and ImageIndex properties. To remove an item, select it and click the Remove button.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 107
Use the Add method of the Items property. ListView1.Items.Add("List item text", 3)
8/16/2011
108
To add columns in the designer Set the control's View property to Details. In the Properties window, click the ellipsis button () next to the Columns property. The ColumnHeader Collection Editor appears. Use the Add button to add new columns. You can then select the column header and set its text (the caption of the column), text alignment, and width.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 109
Set the control's View property to Details. Use the Add method of the list view's Columns property. ' Visual Basic' Set to details viewListView1.View = View.Details' Add a column with width 20 and left alignmentListView1.Columns.Add("File type", 20, HorizontalAlignment.Left)
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 110
Framework basics
CLR CLI CTS MANAGED CODE ASSEMBLY IL
8/16/2011
111
runtime and it forms the heart of the .net framework.all languages have runtime and its the responsibility of the runtime to take care of the code execution of the program.
8/16/2011
112
mechanism for loading and running programs and managing their interactions. This mechanism is described in the Common Language Infrastructure (CLI) The CLI is just a specificationit has to be implemented in order to be useful. An implementation of the CLI is known as a Common Language Runtime (CLR). Microsoft's CLR implementation on the Windows platform is not under ECMA's control, but it is Microsoft's intention that the CLR be a fully compliant implementation of the CLI.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 113
smoothly CLR has CTS .Example in VB you have integer and in c++ you have long these data types are not compatible so the interfacing between the m is very complicated. in order that two different languages can communicate Microsoft introduced common type system. so integer data type in vb6 and int data type in c++ will convert it to system .ini.int32 which is data type of CTS .CLS is subset of CTS.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 114
languages are expected to support.it was always a dream of Microsoft ot unite all different languages in to one umnrella and CLS is one step towards that .microsoft has defined CLS which is nothing but guidelines that language has to follow so that it can communicate with other .NET languages in a seamlesls manner
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 115
Managed code
Managed code runs inside the environment of
CLR that is within .net runtime.in short all IL are managed code.but if you are using some third party software example vb6 or vc++ component they are unmanaged code as .net runtime does not have control over the source code execution of the language.
8/16/2011
116
environment, there arises the need to instantiate and destroy objects. Instantiated objects occupy memory. When objects are no longer in use, the memory they occupy should be reclaimed for use by other objects
8/16/2011
117
Assembly
Assembly is unit of deployment like exe of
dll an assemble consists of one or more files and represents a group of resource type definitions and implementations of those types.an assembnly group of resources type definations and implementation of those types.an assembly may also contain references to other assaemblies . the manifest is part of the assembly thus making the assembly self describing
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 118
to Intermediate Language (IL), also known as Common Intermediate Language (CIL). IL is a machine language that is not tied to any specific machine. Microsoft designed it from scratch to support the CLI's programming concepts. The CLI specifies that all CLR implementations can compile or interpret IL on the machine on which the CLR is running. If the IL is compiled (versus interpreted), compilation can occur at either of two times: Immediately prior to a method in the application being executed At deployment time
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 119
Contd
. The compiled code is not saved to disk, so if the
application is stopped and restarted, the compilation must occur again. This is known as just-in-time (JIT) compilation and is the most common scenario. In the second case, the application is compiled in its entirety at deployment time. IL is saved to .exe and .dll files. When such a file containing IL is executed, the CLR knows how to invoke the JIT compiler and execute the resulting code. Note that on the Microsoft Windows platforms, IL is always compilednever interpreted.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 120
OOP-Concept
Objects
Visual basic allows you to create object by defining class.Class may have properties and methods.Object is a thing which is properties and methods. User defined class can be created in vb.and that classes can be incorporated to projects as a references. Properties are the characteristic and methods are the operation that can be performed on an object.
8/16/2011
121
OOP-Terminology
Encapsulation Inheritance Polymorphism
8/16/2011
122
CLASSES
Instantiating an object
8/16/2011
123
the way that your class allows its properties is to be accessed is through a property procedure. it may contain a get to retrieve a property value and a set to assign a value to the property. Following is the example: Property op1() As Integer Get op1 = no1 End Get Set(ByVal Value As Integer) no1 = Value End Set End Property
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 124
in windows application Dim c as new class name This class name must be add as a reference in a project.
8/16/2011
125
ERROR HANDLING
Error messages can occur while an application is running, either within the Visual Basic .NET environment or as a stand-alone executable. Some of these can also occur during design time or compile time Visual Basic compiler errors occur when the compiler encounters problems in the code. The code causing the errors is marked with a wavy line underneath it in the Code Editor, and when your mouse pauses over the marked code, the error message appears. The messages also appear in the Task List. Visual Basic run-time errors occur when an application attempts to perform an action that the system cannot execute.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 126
8/16/2011
127
Run-Time Errors Run-time errors are those that appear only after you compile and run your code. These involve code that may appear to be correct in that it has no syntax errors, but that will not execute. For example, you might correctly write a line of code to open a file. But if the file is corrupted, the application cannot carry out the Open function, and it stops running. You can fix most runtime errors by rewriting the faulty code, and then recompiling and rerunning it. Logic Errors Logic errors are those that appear once the application is in use. They most often take the form of unwanted or unexpected results in response to user actions. For example, a mistyped key or other outside influence might cause your application to stop working within expected parameters, or altogether. Logic errors are generally the hardest type to fix, since it is not always clear where they originate.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 128
EXCEPTION
Visual Basic supports both structured and unstructured exception (error) handling. By placing specific code in your application, you can handle most of the errors users may encounter and enable the application to continue running. Structured and unstructured error handling allow you to plan for potential errors, preventing them from interfering with the intended purpose of the application.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 129
Consider using exception handling in any method that uses operators that may generate an exception, or that calls into or accesses other procedures that may generate an exception. If an exception occurs in a method that is not equipped to handle it, the exception is propagated back to the calling method , or the previous method. If the previous method also has no exception handler, the exception is propagated back to that method 's caller, and so on. The search for a handler continues up the call stack, which is the series of procedures called within the application. If it fails to find a handler for the exception, an error message is displayed and the application is terminated.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 130
EXCEPTION
Structured Exception Handling In structured exception handling, blocks of code are encapsulated, with each block having one or more associated handlers. Each handler specifies some form of filter condition on the type of exception it handles. When an exception is raised by code in a protected block, the set of corresponding handlers is searched in order, and the first one with a matching filter condition is executed. A single method can have multiple structured exception handling blocks, and the blocks can also be nested within each other. The Try...Catch...Finally statement is used specifically for structured exception handling. For more information Unstructured Exception Handling The On Error statement is used specifically for unstructured exception handling. In unstructured exception handling, On Error is placed at the beginning of a block of code. It then has "scope" over that block; it handles any errors occurring within the block. If the program encounters another On Error statement, that statement becomes valid and the first statement becomes
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 131
8/16/2011
132
TRY..CATCH STATEMENT
Try [ tryStatements ] [ Catch [ exception [ As type ] ] [ When expression ] [ catchStatements ] ] [ Exit Try ]... [ Finally [ finallyStatements ] ]End Try Parts tryStatements Optional. Statement(s) where an error can occur. Can be a compound statement. Catch Optional. Multiple Catch blocks permitted. If an exception occurs while processing the Try block, each Catch statement is examined in textual order to determine if it handles the exception. Exception represents the exception that has been thrown. exception Optional. Any variable name. The initial value of exception is the value of the thrown error. Used with Catch to specify the error caught. type Optional. Specifies the type of class filter. If the value of exception is of the type specified by type or of a derived type, the identifier becomes bound to the exception object. When Optional. A Catch statement with a When clause will only catch exceptions when expression evaluates to True. A When clause is only applied after checking the type of the exception, and expression may refer to the identifier representing the exception.
8/16/2011
134
expression Optional. Must be implicitly convertible to Boolean. Any expression that describes a generic filter. Typically used to filter by error number. Used with When keyword to specify circumstances under which the error is caught. catchStatements Optional. Statement(s) to handle errors occurring in the associated Try block. Can be a compound statement. Exit Try Optional. Keyword that breaks out of the Try...Catch...Finally structure. Execution resumes with the Finally block if present, otherwise with the code immediately following the End Try statement. Not allowed in Finally blocks. Finally Optional. A Finally block is always executed when execution leaves any part of the Try statement. finallyStatements Optional. Statement(s) that are executed after all other error processing has occurred. End Try Terminates the Try...Catch...Finally structure.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 135
EXAMPLE
8/16/2011
136
ADO.NET
ADO.NET is the strategic application-level interface for providing data access services in the Microsoft .NET Platform. You can use ADO.NET to access data sources using the new .NET Framework data providers. These data providers include: .NET Framework Data Provider for SQL Server. .NET Framework Data Provider for OLE DB. .NET Framework Data Provider for ODBC. .NET Framework Data Provider for Oracle. These data providers support a variety of development needs, including middle-tier business objects using live connections to data in relational databases and other stores.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 138
ADO
For applications written in native code, ADO provides a COM-based application-level interface for OLE DB data providers. Similar to ADO.NET, ADO supports a variety of development needs, including the creation of front-end database clients and middle-tier business objects using live connections to data in relational databases and other stores. And, like ADO.NET, ADO can construct client-side recordsets, use loosely coupled recordsets, and handle OLE DB's data shaping rowsets.
8/16/2011
139
OLE DB
OLE DB is the strategic system-level programming interface for
accessing data, and is the underlying technology for ADO as well as a source of data for ADO.NET. OLE DB is an open standard for accessing all kinds of data both relational and non-relational data including: mainframe ISAM/VSAM and hierarchical databases; e-mail and file system stores; text, graphical, and geographical data; and custom business objects. OLE DB provides consistent, high-performance access to data and supports a variety of development needs, including the creation of front-end database clients and middle-tier business objects using live connections to data in relational databases and other stores.
8/16/2011
140
8/16/2011
141
To move data between a data store and your application, you must first
142
The two primary methods for connections are Open and Close. The Open method uses the information in the ConnectionString property to contact the data source and establish an open connection. The Close method shuts the connection down. Closing connections is essential, because most data sources support only a limited number of open connections, and open connections take up valuable system resources. If you are working with data adapters or data commands, you do not have to explicitly open and close a connection. When you call a method of these objects (for example, the data adapter's Fill or Update method), the method checks whether the connection is already open. If not, the adapter opens the connection, performs its logic, and closes the connection again. Methods such as Fill only open and close the connection automatically if it is not already open. If the connection is open, the methods use it but do not close it. This gives you the flexibility to open and close data commands yourself. You might do this if you have multiple data adapters that share a connection. In that case, it is inefficient to have each adapter open and close the connection when you call its Fill method. Instead, you can open the connection, call the Fill method of each adapter, and then close the connection when you are done.
8/16/2011
143
Dim Changes As WindowsApplication12.DataSet1 = New WindowsApplication12.DataSet1 Me.BindingContext(DataSet11, "studentmarks").EndCurrentEdit() Changes = CType(DataSet11.GetChanges,WindowsApplication12.DataSet1) Me.OleDbConnection1.Open() OleDbDataAdapter1.Update(DataSet11) Me.OleDbConnection1.Close() DataSet11.Merge(Changes) DataSet11.AcceptChanges()
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 144
8/16/2011
145
ARRAY
8/16/2011
146
ARRAYLIST COLLECTION
An ArrayList is a sophisticated version of an array. The ArrayList class provides some features that are offered in most Collections classes but are not in the Array class.
8/16/2011
147
Contd
The capacity of an Array is fixed, whereas the capacity of an ArrayList is automatically expanded as required. If the value of the ArrayList.Capacity property is changed, the memory reallocation and copying of elements are automatically done.
8/16/2011
148
Contd
ArrayList provides methods that add, insert, or remove a range of elements. In Array, you can get or set the value of only one element at a time. A synchronized version of ArrayList is easy to create using the Synchronized method. Array leaves it up to the user to implement synchronization.
8/16/2011
149
Contd
ArrayList provides methods that return readonly and fixed-size wrappers to the collection. Array does not.
8/16/2011
150
CONTD
On the other hand, Array offers some flexibility that ArrayList does not. For example: You can set the lower bound of an Array, but the lower bound of an ArrayList is always zero.
8/16/2011
151
Contd..
An Array can have multiple dimensions, while an ArrayList always has exactly one dimension. An Array of a specific type (other than Object) has better performance than an ArrayList because the elements of ArrayList are of type Object and, therefore, boxing and unboxing typically occur if storing or retrieving a value type.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 152
Contd
Array is in the System namespace; ArrayList is in the System.Collections namespace.
8/16/2011
153
Properties
8/16/2011
154
Methods
8/16/2011
Add Addrange Binarysearch Clear Copyto Equals Insert Insertrange Remove Reverse
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 155
HASHTABLE COLLECTION
A Hashtable consists of buckets that contain the elements of the collection. A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections. Each bucket is associated with a hash code, generated using a hash function and based on the key of the element.
8/16/2011
156
Contd
When an object is added to a Hashtable, it is stored in the bucket that is associated with the hash code that matches the object's hash code. When a value is being searched for in the Hashtable, the hash code is generated for that value, and the bucket associated with that hash code is searched.
8/16/2011
157
CONTD
Properties Count Keys Item values Methods Add Remove Contains clear
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 158
SortedList Class
The SortedList class is like a hybrid between
Hashtable and ArrayList. As with Hashtable, SortedList is based on the IDictionary interface; therefore, each element of a SortedList is a key-and-value pair. SortedList provides methods that return only the list of keys or only the list of values. As with ArrayList, a SortedList is a sequence of elements. It is indexed, and is sorted according to a specified comparer. SortedList is unique among all Collections classes in that each element can be accessed three ways: using the key, the value, or the index.
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 159
8/16/2011
Contd
Properties
Methods
8/16/2011
Char class
Char variables are stored as unsigned 16-bit
(2-byte) numbers ranging in value from 0 through 65535. Each number represents a single Unicode character. Direct conversions between the Char data type and the numeric types are not possible, but you can use the AscW and ChrW functions for this purpose.
8/16/2011
161
Contd
Properties
Maxvalue Minvalue
Methods
8/16/2011
String class
Represents a set of unicode characters Properties
Chars Length
8/16/2011
163
Methods
8/16/2011
8/16/2011
165
StringBuilder Class
The String object is immutable. Every time you use
one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 166
Contd
Properties Capacity Chars Length Methods Append Remove Insert Replace Tostring
8/16/2011 NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 167
DATETIME
Represents an instant in time, typically expressed as
Date Dayofweek Dayofyear Hour Minute Month Now Timeofday Today year
NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Kaushar Ghanchi 168
Contd
Methods
8/16/2011
169
8/16/2011
170