Académique Documents
Professionnel Documents
Culture Documents
NET
Deepak Patil
Introduction to VS.NET
Agenda
VS.NET Projects Types of Projects Analyzing structure of project Using Solution Explorer Using Server Explorer Object Browser Toolbox Property Window My First VB.NET App.
Class Library
Class libraries that provide similar functionality to Microsoft ActiveX dynamic-link libraries (DLLs) by creating classes accessible to other applications.
Console Application
Console applications that will run from a command line.
Windows Service
Windows services that will run continuously regardless of whether a user is logged on or not.
Object Browser
Examine Objects and their Members Access Lower-level Items Shows inheritance and interfaces Examine How the .NET Framework Class Libraries Use Inheritance
Tool Box
Property Window
Visual Basic.NET
Leave it in VB6
WebClasses, ActiveX Documents, DHTML Projects
Thinking in VB.NET
Data Types, Type vs. Structure Property Functions, Zero Bound Arrays Default Parameters
New Features
Forms Designer, Declaration Syntax Structured Exception Handling Overloading, Inheritance Free Threading
ADO.NET
Variable
What is a variable? It is a container (with a name) that holds stuff Remember Algebra?
X+3=7 X is a variable. It contains/holds/represents a value, that we can deduce is 4.
Variable
We must dimension variables i.e. tell the computer that you want one before you use it
declare a variable (in C) The computer allocates memory and then you can put what you want in it You can put only something which the variable can hold read DATATYPE.
Data Types
What are Data Types? Data Types restrict what a variable can hold Memory is allocated depending on the data type text, number, date
Text: BITS, Visual, Basic Number: 3, 9, 432156 Dim name as String name = 7 WRONG!
Examples
Rahul Red f1997408
Examples
10 -666 0
Examples
0.00 19.7 -98.3674501
Keywords
Keywords are words with special meaning in a programming language. In Visual Basic .NET, keywords are reserved; that is, they cannot be used as tokens for such purposes as naming variables and subroutines. E.g. Binary, Boolean, ByRef, Byte, ByVal, Auto, integer, Float, else, exit
Dimensioning Variables
Two ways
Dim x as Integer Dim x as Integer = 7 initialized also here
Points to note
You can do it only once per procedure Variables have a scope Access to variables can be defined: Public, Private, etc
Operators
Operators are symbols & specify operations to be performed on one or two operands (or arguments). Operators that take one operand are called unary operators. Operators that take two operands are called binary operators. Type of Operators:
Unary Operators Arithmetic Operators Relational Operators String-Concatenation Operators Logical Operators
Unary Operators
- (unary minus)
The unary minus operator takes any numeric operand. The value of the operation is the negative of the value of the operand. In other words, the result is calculated by subtracting the operand from zero.
Arithmetic Operators
* (multiplication) / (regular division)
The regular division operator is defined for all numeric operands. The result is the value of the first operand divided by the second operand.
\ (integer division)
The integer division operator is defined for integer operands (Byte, Short, Integer, and Long).
The result is the value of the first operand divided by the second operand, then rounded to the integer nearest to zero.
Mod (modulo)
The modulo operator is defined for integer operands (Byte, Short, Integer, and Long). The result is the remainder after the integer division of the operands.
Relational Operators
= (equality) <> (inequality) < (less than) > (greater than) <= (less than or equal to) >= (greater than or equal to) Like TypeOf
String-Concatenation Operators
& and +
The & (ampersand) and + (plus) characters signify string concatenation.
Logical Operators
Logical operators are operators that require Boolean operands. They are:
And
The result is True if and only if both of the operands are True; otherwise, the result is False.
Or
The result is True if either or both of the operands is True; otherwise, the result is False.
Xor
The result is True if one and only one of the operands is True; otherwise, the result is False.
Not
This is a unary operator. The result is True if the operand is False; False if the operand is True.
Statements
Made up of
Keywords (like Dim) Operators Variables Constants Expressions
Statements
Types of statements
Declaration
Dim x% =10
Executable
If Then Else Function calls
Statements
Each statement is a command Each statement can be on a new line or combined together with : Statements can span multiple lines using _ Your program a lot of statements that do interesting things
Variables can be declared and initialized in same line As New syntax does not result in lazy instantiation
Dim i As Integer = 100
Public Class Human Public Name As String = "John Doe" Function Speak() As String Return "Hi, my name is " & Name End Function End Class
Sub MySub(ByVal x As Integer, y As Double) '*** definition End Sub End Class defined with ByVal semantics
Option Explicit On Option Strict On Class MyApp Shared Sub Main() '*** my application code End Sub End Class
'*** source file: MyApp.vb '*** build target: MyApp.exe '*** references: MyLibrary.dll Class MyApp Shared Sub Main() Dim obj As New Human obj.Name = "Bob" Dim msg As String = obj.Speak System.Console.WriteLine(msg) End Sub End Class
A console-based consoleapplication
Agenda
If, then, End If If, Then, Else, End If Select Case While Statement Do Loop For next Arrays
If Then End If
Allows conditional branching in code
If stars > 4 Then rating = Super Hit End If
Select Case
A Select Case statement executes statements based on the value of an expression. The expression must be classified as a value and its type must be a primitive type or Object. When a Select Case statement is executed, the Select expression is evaluated first, and the Case statements are then evaluated in order of textual declaration. The first Case statement that evaluates to True has its block executed. If no Case statement evaluates to True and there is a Case Else statement, that block is executed. Once a block has finished executing, execution passes to the end of the Select statement.
Select Case
Syntax:
Select Expression1 Case 1 Statement Block for Case 1 Case 2 Statement Block for Case 2 Case N Statement Block for Case N Case Else Catch All End Select
Select Case
dim income as double select case income case 0 To 100000 tax=0 case 0 To 100000 tax=0 case 100001 To 150000 tax=0.10 * (income-100000) case 150001 To 200000 tax=0.15*(income-150000) + 5000 case Else tax=0.20*(income-200000) + 7500 end select
Select Case
Select number case 1, 2, 3 txtresult.text= 1 case 4 To 10 txtresult.text= 2 case Is < 20 txtresult.text= 3 case Is > 20 txtresult.text= 4 End Select
While statement
Used to iterate through a section of code Iteration could be indefinite Has a break condition
Control comes out when this condition is met
While statement
Syntax: While <Expr> [statements] End While
While statement
Example 1
Dim counter as Integer = 0 Dim value as integer = 0 while value < 30 counter = counter + 1 value = value + 10 end while Msgbox The while loop & counter & times.
Do Loop
Syntax: Do[{while | Until} condition] [statements] [Exit Do] [statements] Loop
Do While
Continues to loop while a certain condition (expression) evaluates to TRUE
Stops when condition evaluates to FALSE
Do While Example
Dim value as Integer Dim counter as Integer Value = 11 Counter = 0 Do While value > 10 counter = counter + 1 value = value 1 Loop Msgbox (THE DO WHILE LOOP: + counter + times.
Do Until
Continues to loop until a certain condition (expression) evaluates to TRUE
Stops when condition evaluates to TRUE
Do Until Example
Dim value as Integer Dim counter as Integer Value = 9 Counter = 0 Do Until value = 10 counter = counter + 1 value = value + 1 Loop Msgbox (THE DO UNTIL LOOPED: + CStr(counter) + times.)
Do While Variant
Depending on the check condition
Check first and then execute [previous case] Execute first and then Check
Do Until Variant
Depending on the check condition
Check first and then execute [previous case] Check last and then execute
For Next
When it is known before hand how many times the iteration will happen. Syntax: For x = i To j [statements] Next
For-Next
Example 1: For Counter = 1 To 1000 skip any values between 100 and 600 If Counter = 100 Then Counter = 601 set text value Text1.Text = Counter Text1.Refresh Update Text1 Next Counter
For-Next
Steps
When the jump has to be something other than 1 Ex: For Counter = 1 To 1000 Step 5 skip any values between 100 and 600 If Counter = 100 Then Counter = 601 set text value Text1.Text = Counter Text1.Refresh Update Text1 Next Counter
For-Next
Looping backwards For Counter = 2000 To 1 Step -1 counting back from 2000 to 1 Text1.Text = Counter Text1.Refresh Update Text1 Next Counter Msgbox "Count down finished"
Exit For
For I = 1 To 10 if I = 7 then exit for end if Text1.Text = Counter Text1.Refresh Update Text1 Next
Arrays in VB.NET
An array is a reference type that contains variables accessed through indices corresponding in a one-to-one fashion with the order of the variables in the array. The variables contained in an array, also called the elements of the array, must all be of the same type, and this type is called the element type of the array. An array has a rank that determines the number of indices associated with each array element. The rank of an array determines the number of dimensions of the array.
Arrays in VB.NET
Array declaration:
Dim arr(5) as Integer Arr(0) = 1 Arr(1) = 2 Arr(2) = 3 Etc OR Dim arr(5) as Integer = (1, 2, 3, 4, 5) ReDim Preserve arr(10)
Arrays in VB.NET
Array Declaration:
dim square(2,2) as integer square(0,0)=1 square(0,1)=2 square(1,0)=3 OR Dim rectArray(,) As Integer = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}} OR Dim colors(2)() as String colors(0)=New String(){"Red","blue","Green"} colors(1)=New String(){"Yellow","Purple","Green","Violet"} colors(2)=New String(){"Red","Black","White","Grey","Aqua"}
Array Methods
Array.GetLowerBound(rank) Array.GetUpperBound(rank) Array.Sort(arr) Array.BinarySearch(arr, element) Array.Reverse(MyIntArray) Array.GetValue(index) Array.IndexOf(arr, element) Array.LastIndexOf(arr, element) Array.copy()
Array Property
Array.Length Array.IsReadOnly (always false) Array.IsFixedSize (always true)
Scope of Variables
It refers to as the visibility and life of a data item or object Types: Local/Procedural Scope Block Scope Module Scope
Local Scope
Such variable are visible only inside that particular module/ procedure/ function.
E.g.: Private Sub button1_Click
Dim i as integer=10 Dim k=i/5
End Sub
Block Scope
If a variable is declared inside a code block (a set of statements that is terminated by an End..., Loop, or Next statement), then the variable has block-level scope ; that is, it is visible only within that block.
For example, consider the following code: If x <> 0 Then Dim rec As Integer rec = 1/x End If MsgBox CStr(rec)
Module Scope
OR
It means that every procedure within that module has the full access to the data items. Module scope limits access to the module in which the definition occurs.
IMP: If two variables with the same name are both in scope, the most recently defined variable is the variable that is being accessed.
Subroutines/ Functions
They are set of instructions designed to accomplish one specific task.
They eliminates duplicate code Promotes modularity Which further leads to CODE RESUE
End Function The variables sInput and iCount are the parameters of this function. Note that each parameter has an associated data type. Now, when we call this function, we must replace the parameters by variables, constants, or literals, as in: s = RepeatString("Donna", 4) The items that we use in place of the parameters are called arguments.
Passing Arguments
Arguments can be passed in 2 ways:
ByVal (Call by value): Passing by value means that the actual value of the argument is passed to the function. ByRef (Call by reference) if we pass an object variable by reference, we are passing the address of the variable.
Optional Arguments
The following rules apply to optional arguments:
Every optional argument must specify a default value, and this default must be a constant expression (not a variable). Every argument following an optional argument must also be optional.
New concepts in OOP Shared members Overloading methods Constructors Inheritance Overridable methods and polymorphism Interfaces Delegates Object finalization and disposal
OOP Fundamentals
Encapsulation
Encapsulation is all about the separation between implementation and interface. It implements Data Hiding
Abstraction
The ability to create an abstract representation of a concept in code. Its a mechanism and practice to reduce and factor out details irrelevant to the user.
Inheritance
It allows you to derive new classes from other classes. It is intended to help reuse of existing code with little or no modification.
Polymorphism
The idea of allowing the same definitions to be used with different types of data (specifically, different classes of objects), resulting in more general and abstract implementations.
Class
The idea is that classes are a type. Class defines the behavior of possibly many objects (instances). A class is a blueprint that defines the variables and the methods common to all objects of a certain kind.
Object
If class is a blueprint, then object is the implementation of that blueprint. Each object has data members, corresponding to what objects knows, and data functions, corresponding to what an object can do. A region of storage with associated semantics.
Properties
Properties are retrieved and set like fields, but are handled with the Property Get and Property Set procedures They provide more control on how values are set or returned Methods Methods represent the object's built-in procedures. They are used to implement the behavior of the class. Events allow objects to perform actions whenever a specific occurrence takes place.
Events
Creating Class
To create a class, you only need to use the Class statement, which, like other compound statements in Visual Basic, needs to end with End Class:
Syntax: Public Class DataClass End Class
Example of a Class
Public Class Employee Private Name as String Public Salary as Double End Class
Public Class Employee Public Salary As Double End Class Public Class Employee Public Const PSRN As Integer = 0 End Class
Member Variables
Private
Available only to code within the class
Friend
Available only to code within our project/component
Protected
Available only to classes that inherit from our class
Protected Friend
Available only to code within our project/component and classes that inherit from our class
Public
Available to code outside our class
Creating Methods
As discussed earlier, methods represent the object's built-in procedures. You define methods by adding procedures, either Sub procedures or functions, to your class.
Public Class Animal Public Sub Eating() MsgBox("Eating...") End Sub Friend Sub Sleeping() MsgBox("Sleeping...") End Sub End Class
Creating Methods
Public Class Employee Class Employee defined here Private m_Tax as double Declared Data member Public Sub Set_Tax(Byval Value as double) Declared Function M_Tax=Value to set value End Sub another such function defined below Public Function GET_PAYABLE_TAX() As Double GET_PAYABLE_TAX = m_TAX End Function End Class class employee end here
Creating Properties
If you often don't want to give code outside an object direct access to the data in the object then, you can use properties, which use methods to set or get an internal value.
Syntax: Public Property <prop_name>( ) as <ret_type> Get Return PropertyValue End Get Set(ByVal Value As String) PropertyValue = Value End Set End Property
Creating Properties
Public Property SET_NAME() As String
property name SET_NAME with return type as string Get get starts here for getting this value
SET_NAME = m_NAME End Get get ends here Set(ByVal Value As String) set starts here m_NAME = Value setting the value of the data End Set End Property
member here set property ends here
Parameterized Properties
Pass parameters to properties Public Property Pin(ByVal Pincode as String) As String Get Write the code to get End Get Set (ByVal value as String) Write the code to set End Set
Default Property
Sets the default value
Default Public Property IsActive (ByVal value As String) As Boolean Get Return True End Get Set(ByVal value as Boolean) m_Is_Active = value End set End Property
Constructor
A constructor is a special member function whose task is to initialize the objects of it's class. A constructor is invoked whenever an object of it's associated class is created. If a class contains a constructor, then an object created by that class will be initialized automatically.
Constructor
Here are the characteristics of a constructor: Always defined as a Sub. It therefore does not have a return value. Regardless the name of the class, the constructor in VB.NET is called New. In most cases, a constructor has a Public access modifier. A class can have multiple constructors.
Constructor
e.g.
Public Sub New() m_name = "" m_nickname = "" m_dob = Now.Date m_email = "" m_ph = 0 m_mob = 0 m_address = "" m_org = "" End Sub
Overloading Constructors
Public Class Employee private m_name as string public sub new() m_name= End sub public sub new(byval name as string) m_name = name End sub End Class
Destructor
Destructors run when an object is destroyed. Within a destructor we can place code to clean up the object after it is used. We use Finalize method in Visual Basic for this and the Finalize method is called automatically when the .NET runtime determines that the object is no longer required. When working with destructors we need to use the overrides keyword with Finalize method as we will override the Finalize method built into the Object class.
Destructor
Protected Overrides Sub finalize() this distructor is called by Garbage Collector... its called when GC feels like freeing the memory which can even be long after the application exits MsgBox("DIstructor Called Again BY 'GC' this time) End Sub
Creating Objects
There are two ways for creating an object. They are:
- Dim data As New DataClass() - Dim data As DataClass = New DataClass()
DEMO
Events
Objects can raise events. Handles
Private Sub btnObject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click Private Sub MyClickMethod(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click,button2.Click
WithEvents
Makes any events from an object available for use. Cannot be used to declare a variable of a type that doesnt raise events.
Handling Events
Raise Event
Define Event
Public Event Brake( )
Raise Event
RaiseEvent Brake()
Interface - IDisposable
Finalize
GC class Finalize immediately before it collects an object that is no longer required by application. Protected scope and Overrides.
IDisposable
Force the object cleanup. Public Class Car Implements IDisposable
Shared Variables
Variables value should be shared across all objects within the application.
Private Shared sCounter As Integer
2 Ways to call
Call directly from class Call from instance
Shared Method
Common across all instances of the class.
Shared methods doesnt belong to any specific object Cant access any instance variables from any objects. Only variables available for use within shared method are shared variables,parameters passed into method or variables declared locally within the method itself.
Shared Properties
Follow same rules as regular methods
Can interact with shared variables, but not member variables Can invoke other shared methods or properties Cannot invoke instance methods without first creating an instance of class.
Inheritance
New class can be based on existing class, inheriting its interface and functionality from original class. Also referred as generalization or is-a relationship. Superclass /Parent Class/ Base Class Derived Class Variable Access
Variables and methods that are Private are available only within that class. Variables and methods that are Public in one class can be called from other class. Variables and methods that are Friend are available between classes if both the classes are in same VB.NET project.
Overloading Methods
Overloads Keyword
Overriding Methods
Override the behavior of methods on base class Overridable keyword
MyBase Keyword
Invoke the methods directly from the base class.
Inheritance
Inherits
Used to indicate that a class should derive from existing class inheriting interface and behavior from that class
Overloading
Overloading a method from base class and is done by Overloads keyword.
Overriding Methods
Not only Extend the original functionality but actually change or entirely replace the functionality from base class.
Overridable
If we dont use the keyword when declaring a method, it is non virtual.
Overrides MyBase
Abstract Class
Create a class so that it can only be used as base class for inheritance.
MustInherit keyword
Preventing anyone from creating objects based directly on the class and requiring them instead to create a subclass and then create objects based on that subclass.
Public MustInherit Class Vehicle
MustOverride keyword
Base class also relied on subclass to provide some behavior in order to function properly. Class that contaisn methods with MustOverride should be declared with MustInherit
Interface
Define the Interface Public Interface iPrint Function Definitions here!
End Interface
Implementing Interface
Using Implements keyword To implement an interface, we must implement ALL the methods and properties defined by that interface.
Error Handling
All .NET exceptions inherit from System.Exception
Namespace System
Class ApplicationException SystemException VB6Exception System.Data InvalidConstraintException System.IO IOException System.Runtime.InteropServices COMException System.XML XmlException
On Error
On Error Goto ErrorHandler Write ErrorHandler
Try..Catch..Finally
Try Catch Finally Exit Try Nested Try
Clipboard
Temporary memory area that holds copied objects Copied objects can be used in Paste Operation. DataObject Clipboard
Assembly
Private Shared
Public Key
Guarantees that the strong name is unique. Also guarantees that a referenced assembly cant be replaced from different source.
Culture.
Public/Private Key
If something is encrypted using a public key, it can be decrypted by using the corresponding private key, but it is not possible with the public key. Also works other way round! Always created as pair.
Windows Forms
System.Windows.Forms Design ComponentModel
Windows Forms
Use of Form Reuse of Form Methods and Properties
Form
Properties
AcceptButton CancelButton ControlBox Font Location Maximize/Minimize Size StartPosition TopMost Window State
Form
Events
Load Event Activated Event (Occurs when the form is activated in code or by the user.) Closing Event Closed Event (Occurs when the form is closed) Resize
Methods
Close Hide Show Focus Dispose
Controls
A control is an object that can be drawn on to the Form to enable or enhance user interaction with the application. Example textbox, radiobutton, checkbox etc All these Windows Controls are based on the Control class, the base class for all controls. Visual Basic allows us to work with controls in two ways: at design time and at runtime. Some of the properties of this class are: Allowdrop DataBindings Size Anchor Dock Width Backcolor Enable TabIndex Bottom Focused Text CanFocus Forecolor Visible etc CanSelect Font Cursor Name
Textbox
Properties
Text Maxlength Multiline Passwordchar Scrollbars SelectedText SelectionStart TextAlign TextLength
Methods
AppendText Clear Cut Copy Paste Select
Events
Click DoubleClick GotFocus Keydown KeyUp KeyPress MouseHover TextChanged
Label
Properties
Text Name BackColor BorderStyle Image Location Size
Methods
Focus Hide Show Dispose ToString
Events
Click DoubleClick GotFocus Keydown KeyUp KeyPress MouseHover TextChanged
Visible
Button
Properties
Text Name BackColor BorderStyle Image Location Size
Methods
Focus Hide Show Dispose ToString
Events
Click DoubleClick GotFocus Keydown KeyUp KeyPress MouseHover TextChanged
Visible
CheckBox
Property
Checked CheckState
Methods
OnClick
Events
Click CheckedChange
RadioButton
Properties
Appearance BackgroundImage Checked
Methods
OnClick
Events
Click CheckedChange
ListBox
Properties
Items SelectedIndex SelectedItem HorizontalScrollbar MultiColumn SelectionMode Sorted
Events
SelectedIndexChanged SelectedValueChanged
ListBox
To add item Listbox1.items.add(<value>) To count no. of items Listbox1.items.count To get the selected value Listbox1.selectedItem To remove item Listbox1.items.RemoveAt(index_value) To remove all the items Listbox1.items.Clear()
ComboBox
Properties
Items SelectedIndex SelectedItem Text* Sorted DropDownStyle MaxDropDown
Events
SelectedIndexChanged SelectedValueChanged
ScrollBars
Property
SmallChange LargeChange Maximum Minimum Value
Events
Scroll ValueChanged
ScrollBars
Property
SmallChange LargeChange Maximum Minimum Value
Events
Scroll ValueChanged
PictureBox
The Windows Forms PictureBox control is used to display graphics in bitmap, GIF, JPEG, metafile, or icon format. Properties:
Image Borderstyle SizeMode
PictureBox
To display a picture at design time Draw a PictureBox control on a form. On the Properties window, select the Image property, then click the ellipsis button to display the Open dialog box. If you are looking for a specific file type (for example, .gif files), select it in the Files of type box. Select the file you want to display.
PictureBox
To set a picture programmatically Set the Image property using the FromFile method of the Image class. e.g.
PictureBox1.Image = Image.FromFile(path)
DateTimePicker
The DateTimePicker control is used to allow the user to select a date and time, and to display that date/time in the specified format. Major properties are:
MaxDate Property Gets or sets the maximum date and time that can be selected in the control MinDate Property Gets or sets the minimum date and time that can be selected in the control
DateTimePicker
Format Property Gets or sets the format of the date and time displayed in the control. CustomFormat Property Gets or sets the custom date/time format string. with the appropriate formatting or custom formatting applied. Value Property Gets or sets the date/time value assigned to the control.
Timer Control
Implements a timer that raises an event at user-defined intervals. Properties:
Enabled Property Gets or sets whether the timer is running. Interval Property Gets or sets the time, in milliseconds, between timer ticks. Event: Tick Event Occurs when the specified timer interval has elapsed and the timer is enabled.
Timer Control
Methods:
OnTick Method Raises the Tick event. Start Method Starts the timer. Stop Method Stops the timer.
Richtext Box
Properties Color Font Forecolor Zoomfactor WordWrap SelectionColor SelectionFont SelectedText SelectionLength SelectionIndent SelectionRightIndent SelectionBullet SelectionAlignment SelectionHangingIndent
Richtext Box
Methods LoadFile SaveFile Find Undo Redo Events LinkClicked
DialogBox Controls
OpenFileDialog SaveFileDialog FontDialog ColorDialog
DialogResult Enumeration
Specifies identifiers to indicate the return value of a dialog box.
Abort Cancel Ignore Ok Yes No Retry
OpenFileDialog
OpenFileDialog
OpenFileDialog's are supported by the OpenFileDialog class and they allow us to select a file to be opened. Properties:
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.
OpenFileDialog
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. MultiSelect: This property when set to True allows to select multiple file extensions. ReadOnlyChecked: Gets/Sets whether the read-only checkbox is checked.
OpenFileDialog
OpenFileDialog1.Filter = Text files (*.txt)|*.txt|" & "All files|*.* OpenFileDialog1.Filter =All Image Files| *.bmp; *.gif; *.jpg Dim myfile = OpenFileDialog1.Filename OpenFileDialog1. InitialDirectory=c:\abc OpenFileDialog1.Title = "My Image Browser" msgbox(OpenFileDialog1.OpenFile())
OpenFileDialog
One approach is to use the ShowDialog method to display the Open File dialog box, and use an instance of the StreamReader class to open the file.
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Dim sr As New System.IO.StreamReader(OpenFileDialog1.FileName) MessageBox.Show(sr.ReadToEnd) sr.Close()
End if
OpenFileDialog
Use the ShowDialog method to display the dialog box and the OpenFile method to open the file.
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Cursor Files|*.cur openFileDialog1.Title = "Select a Cursor File" If openFileDialog1.ShowDialog() = DialogResult.OK Then Me.Cursor = New Cursor(openFileDialog1.OpenFile())
End If
OpenFileDialog
Dim sr as StreamReader With OpenFileDialog1 .Filter = "Text files (*.txt)|*.txt|" & "All files|*.*" If .ShowDialog() = DialogResult.OK Then FileName = .FileName sr = New StreamReader(.OpenFile) RichTextBox1.Text = sr.ReadToEnd() End If End With
SaveFileDialog
SaveFileDialog
Save File Dialog's are supported by the SaveFileDialog class and they allow us to save the file in a specified location. Properties:
Same as that of OpenDialog Box OverwritePrompt
Gets or sets a value indicating whether the Save As dialog displays a warning if the user specifies a file name that box already exists.
SaveFileDialog
To save file 1. Open SaveFileDialog Box 2. Declare a stream writer 3. Get the Filename 4. Write into that Filename(from a perticular control)
SaveFileDialog
With SaveFileDialog1
.FileName = FileName .Filter = "Text files (*.txt)|*.txt|" & "All files|*.*" If .ShowDialog() = DialogResult.OK Then FileName = .FileName End WIth
sw = New StreamWriter(FileName)
FontDialog
FontDialog
Represents a common dialog box that displays a list of fonts that are currently installed on the system. Properties: Color Property Gets or sets the selected font color. Font Property Gets or sets the selected font. MaxSize Property Gets or sets the maximum point size a user can select. ShowColor Property Gets or sets a value indicating whether the dialog box displays the color choice.
FontDialog
MinSize Property
Gets or sets a value indicating whether the dialog box contains controls that allow the user to specify strikethrough, underline, and text color options. e.g.
FontDialog1.Font =textBox1.Font fontDialog1.Color=textBox1.ForeColor FontDialog1.MaxSize = 32 FontDialog1.MinSize = 18 If FontDialog1.ShowDialog() = DialogResult.OK Then TextBox1.Font =FontDialog1.Font End if
ColorDialog
ColorDialog
Represents a common dialog box that displays available colors along with controls that allow the user to define custom colors. Properties: AllowFullOpen Property Gets or sets a value indicating whether the user can use the dialog box to define custom colors. AnyColor Property Gets or sets a value indicating whether the dialog box displays all available colors in the set of basic colors
ColorDialog
Color Property
Gets or sets the color selected by the user.
CustomColors Property
Gets or sets the set of custom colors shown in the dialog box.
FullOpen Property
Gets or sets a value indicating whether the controls used to create custom colors are visible when the dialog box is opened
SolidColorOnly Property
Gets or sets a value indicating whether the dialog box will restrict users to selecting solid colors only.
ColorDialog
e.g. Dim MyDialog As New ColorDialog()
MyDialog.AnyColor = True MyDialog.SolidColorOnly = False MyDialog.AllowFullOpen = True MyDialog.CustomColors = New Integer() {6916092, 15195440} If (MyDialog.ShowDialog() = DialogResult.OK) Then textBox1.ForeColor = MyDialog.Color
End If
Main Menu
Menus are those controls that allow the user to make selections In Visual Basic, the MenuStrip control represents the container for the menu structure of a form Menus are made up of MenuItem objects that represent the individual parts of a menu
Menu Items
Menus like File or Edit and the actual items in such menus are supported with the MenuItem class
Properties: Checked Property Gets or sets a value indicating whether a check mark appears next to the text of the menu item. MdiList Property Gets or sets a value indicating whether the menu item will be populated with a list of the Multiple Document Interface (MDI) child windows that are displayed within the associated form.
Menu Items
Shortcut Property Gets or sets a value indicating the shortcut key associated with the menu item. ShowShortcut Property Gets or sets a value indicating whether the shortcut key that is associated with the menu item is displayed next to the menu item caption. Text Property Gets or sets a value indicating the caption of the menu item. Visible Property Gets or sets a value indicating whether the menu item is visible.
MenuItem.Visible = False
MenuItem5.Enabled = False
MDI Applications
MDI (Multiple Document Interface) Application is an application in which we can view and work with several documents at once. To create an MDI Application: Select a Form and in it's Properties Window under the Windows Style section, set the property IsMdiContainer to True. Setting it to true designates this form as an MDI container for the child windows.
MDI Applications
CREATING MDI CHILD FORMS:
An vital constituent of Multiple Document Interface (MDI) Applications is the MDI child forms, as these are the main windows for client interaction. To create MDI child forms:
Form frmchild = new Form() frmchild.MDIParent = me frmchild.Show()
MDI Applications
Determining the Active MDI Child To specify the correct form, use the ActiveMDIChild property, which returns the child form that has the focus or that was most recently active. e.g.
Dim activeChild As Form = Me.ActiveMdiChild
MDI Applications
1.
2.
3.
MDI Applications
ARRANGING CHILD FORMS:
Applications will have menu commands for actions such as Tile, Cascade, and Arrange, with concerning to the open MDI child forms. One can use the LayoutMDI method with the MDILayout enumeration to rearrange the child forms in an MDI parent form.
e.g.
DEMO
COM
Default Interop Assembly
TlbImp.exe Tlbimp MCalculator.dll /out:MCalculatorNet.dll /verbose
Late Binding
Reflection
Type.GetTypeFromProgID
Create Instance
Activator.CreateInstance
Invoke Member
Parameter 1: Method to call Parameter 2: BindingFlags enumeration tells to invoke the method Parameter 3: Language specific binding information Parameter 4: Reference to COM object. Parameter 5: Array of objects representing the arguments for method.
Creating Controls
Creating/Extending Control Extender /Ambient Creating User Control
Reflection
Ability to inspect and manipulate program elements at runtime. Allows you:
Enumerate the members of a type Instantiate a new object Execute the members of an object Find out information about a type Find out information about an assembly Create and compile new assembly.
System.Type System.Reflection
System.Type class
Holds the reference to a type Dim t As Type Dim d As Double = 10 t = d.GetType()
Q/A
Any Questions please?