dotnet theory

135
Advanced Visual and Windows Programming(BCA-205) NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONS Subject:Advance visual and windows programming(BCA-205) Subject Code :BCA-205 Faculty:Prof.Kaushar Ghanchi Navgujarat BCA Page 1 of 135

Upload: api-19969696

Post on 18-Nov-2014

760 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

NAVGUJARAT COLLEGE OF COMPUTER APPLICATIONSSubject:Advance visual and windows programming(BCA-205)Subject Code :BCA-205Faculty:Prof.Kaushar Ghanchi

Navgujarat BCA Page 1 of 98

Page 2: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

The .NET Framework

The .NET Framework is the next iteration of Microsoft's platform for developing component-based software. It provides fundamental advances in runtime services for application software. It alsosupports development of applications that can be free of dependencies on hardware, operating system, and language compiler.This chapter provides an overview of the architecture of the .NET Framework and describes the base features found in the core of its class library.

Common Language Infrastructure (CLI) and Common LanguageRuntime (CLR)

At the heart of the .NET Framework is a new mechanism for loading and running programs and managing their interactions. This mechanism is described in the Common Language Infrastructure (CLI), a specification for a runtime environment that allows software components to:Pass data between each other without regard to the programming language in which each component is on paperExecute on different operating systems and on different hardware platforms without having to recompile the high-level source code (a low-level compilation still automatically occurs on the target platform, as will be discussed in this chapter)

Although the CLI specification was created by Microsoft, it has since been submitted to the ECMA standards organization (http://www.ecma.ch), which now has responsibility and control over it.The CLI is just a specification—it 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. As of this writing, the CLI has not been implemented on non- Windows platforms, but Microsoft and others have announced intentions to do so.The CLI specifies how executable code is loaded, run, and managed. The portion of the CLR that performs the tasks of loading, running, and managing .NET applications is called the virtual execution system (VES). Code run by the VES is called managed code .The CLI greatly expands upon concepts that exist in Microsoft's Component Object Model (COM). As its core feature, COM specifies how object interfaces are laid out in memory. Any component that can create and consume this layout can share data with other components that do the same. COM was a big step forward when it was introduced (circa 1992), but it has its shortcomings.

Common Type System (CTS)

The CLI specification defines a rich type system that far surpasses COM's capabilities. It's called the Common Type System (CTS). The CTS defines at the runtime level how types are declared and used.

Navgujarat BCA Page 2 of 98

Page 3: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Previously, language compilers controlled the creation and usage of types, including their layout in memory. This led to problems when a component written in one language tried to pass data to a component written in a different language. Anyone who has written Visual Basic 6 code to call Windows API functions, for instance, or who has tried to pass a JavaScript array to a componentwritten either in Visual Basic 6 or C++, is aware of this problem. It was up to the developer to translate the data to be understandable to the receiving component. The CTS obliterates this problem by providing the following features:

Primitive types (Integer, String, etc.) are defined at the runtime level. Components can easily pass instances of primitive types between each other because they all agree on how that data is formatted.Complex types (structures, classes, enumerations, etc.) are constructed in a way that is defined at the runtime level. Components can easily pass instances of complex types between each other because they all agree on how complex types are constructed from primitive types. All types carry rich type information with them, meaning that a component that is handed an object can find out the definition of the type of which the object is an instance. This is analogous to type libraries in COM, but the CTS is different because the type information ismuch richer and is guaranteed to be present.

Common Language Specification (CLS)

The CLI defines a runtime that is capable of supporting most, if not all, of the features found in modern programming languages. It is not intended that all languages that target the CLR will support all CLR features. This could cause problems when components written in different languages attempt to interoperate. The CLI therefore defines a subset of features that are considered compatible across language boundaries. This subset is called the Common Language Specification (CLS).Vendors creating components for use by others need to ensure that all externally visible constructs (e.g., public types, public and protected methods, parameters on public and protected methods, etc.) are CLS-compliant. This ensures that their components will be usable within a broad array of languages, including Visual Basic .NET. Developers authoring components in Visual Basic .NET have an easy job because all Visual Basic .NET code is CLS-compliant (unless the developer explicitly exposes a public or protected type member or method parameter that is of a non-CLS-compliant type).Because Visual Basic .NET automatically generates CLS-compliant components, this book does not describe the CLS rules. However, to give you a sense of the kind of thing that the CLS specifies, consider that some languages support a feature called operator overloading . This allows the developer to specify actions that should be taken if the standard operator symbols (+, -, *, /, =, etc.) are used on user-defined classes. Because it is not reasonable to expect that all languages should implement such a feature, the CLS has a rule about it. The rule states that if a CLS-compliant component has public types that provide overloaded operators, those types must provide access to that functionality in another way as well (usually by providing a public method that performs the same operation).

Intermediate Language (IL) and Just-In-Time (JIT) CompilationAll compilers that target the CLR compile source code 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 executedAt deployment timeIn the first case, each method is compiled only when it is actually needed. After the method is

Navgujarat BCA Page 3 of 98

Page 4: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

compiled, subsequent calls bypass the compilation mechanism and call the compiled code directly. 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 compiled—never interpreted.

MetadataSource code consists of some constructs that are procedural in nature and others that are declarative in nature. An example of a procedural construct is:someObject.SomeMember = 5This is procedural because it compiles into executable code that performs an action at runtime.Namely, it assigns the value 5 to the SomeMember member of the someObject object.In contrast, here is a declarative construct:Dim someObject As SomeClassThis is declarative because it doesn't perform an action. It states that the symbol someObject is avariable that holds a reference to an object of type SomeClass.In the past, declarative information typically was used only by the compiler and did not compile directly into the executable. In the CLR, however, declarative information is everything! The CLR uses type and signature information to ensure that memory is always referenced in a safe way. The JIT compiler uses type and signature information to resolve method calls to the appropriate target code at JIT compile time. The only way for this to work is for this declarative information to be included alongside its associated procedural information. Compilers that target the CLR therefore store both procedural and declarative information in the resulting .exe or .dll file. The procedural information is stored as IL, and the declarative information is stored as metadata. Metadata is just the CLI's name for declarative information.

Modules and Assemblies

A module is an .exe or .dll file. An assembly is a set of one or more modules that together make up an application. If the application is fully contained in an .exe file, fine—that's a one-module assembly. If the .exe is always deployed with two .dll files and one thinks of all three files as comprising an inseparable unit, then the three modules together form an assembly, but none of them does so by itself. If the product is a class library that exists in a .dll file, then that single .dll file is an assembly. To put it in Microsoft's terms, the assembly is the unit of deployment in .NET.An assembly is more than just an abstract way to think about sets of modules. When an assembly is deployed, one (and only one) of the modules in the assembly must contain the assembly manifest, which contains information about the assembly as a whole, including the list of modules contained in the assembly, the version of the assembly, its culture, etc.

Memory Management and Garbage CollectionIn any object-oriented programming environment, there arises the need to instantiate and destroyobjects. Instantiated objects occupy memory. When objects are no longer in use, the memory they occupy should be reclaimed for use by other objects. Recognizing when objects are no longer being used is called lifetime management, which is not a trivial problem. The solution the CLR uses has implications for the design and use of the components you write, so it is worth understanding.In the COM world, the client of an object notified the object whenever a new object reference waspassed to another client. Conversely, when any client of an object was finished with it, the clientnotified the object of that fact. The object kept track of how many clients had references to it. When that count dropped to zero, the object was free to delete itself (that is, give its memory back to the memory heap). This method of lifetime management is known as reference counting. Visual Basic programmers were not necessarily aware of this mechanism because the Visual

Navgujarat BCA Page 4 of 98

Page 5: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Basic compiler automatically generated the low-level code to perform this housekeeping. C++ developers had no such luxury.Reference counting has some drawbacks:A method call is required every time an object reference is copied from one variable to anotherand every time an object reference is overwritten.Difficult-to-track bugs can be introduced if the reference-counting rules are not precisely followed.Care must be taken to ensure that circular references are specially treated (because circularreferences can result in objects that never go away).The CLR mechanism for lifetime management is quite different. Reference counting is not used.Instead, the memory manager keeps a pointer to the address at which free memory (known as the heap) starts. To satisfy a memory request, it just hands back a copy of the pointer and thenincrements the pointer by the size of the request, leaving it in a position to satisfy the next memory request. This makes memory allocation very fast. No action is taken at all when an object is no longer being used. As long as the heap doesn't run out, memory is not reclaimed until the application exits. If the heap is large enough to satisfy all memory requests during program execution, this method of memory allocation is as fast as is theoretically possible, because the only overhead is incrementing the heap pointer on memory allocations.If the heap runs out of memory, there is more work to do. To satisfy a memory request when the heap is exhausted, the memory manager looks for any previously allocated memory that can be reclaimed. It does this by examining the application variables that hold object references. The objects that these variables reference (and therefore the associated memory) are considered in use because they can be reached through the program's variables. Furthermore, because the runtime has complete access to the application's type information, the memory manager knows whether the objects contain members that reference other objects, and so on. In this way, the memory manager can find all of the memory that is in use. During this process, it consolidates the contents of all this memory into one contiguous block at the start of the heap, leaving the remainder of the heap free to satisfy new memory requests.This process of freeing up memory is known as garbage collection (GC), a term that also applies to this overall method of lifetime management. The portion of the memory manager that performsgarbage collection is called the garbage collector. The benefits of garbage collection are:No overhead is incurred unless the heap becomes exhausted.It is impossible for applications to cause memory leaks.The application need not be careful with circular references.Although the process of garbage collection is expensive (on the order of a fraction of a second when it occurs), Microsoft claims that the total overhead of garbage collection is on average much less than the total overhead of reference counting (as shown by their benchmarks). This, of course, is highly dependent on the exact pattern of object allocation and deallocation that occurs in any given program.

.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

Navgujarat BCA Page 5 of 98

Page 6: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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.

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.

What are Web Services?

Web Services are the applications that run on a Web Server and communicate with other applications. It uses a series of protocols to respond to different requests. The protocols on which Web Services are built are listed below: UDDI: Stands for Universal Discovery and Description Integration WSDL: Stands for Web Services Description Language SOAP: Stands for Simple Object Access Protocol XML, HTTP and SMTP

EDITIONS OF VB .NET Academic Edition Professional Edition Enterprise Developer Edition Enterprise Architect Edition

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 BCA Page 6 of 98

Page 7: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

TYPES OF FILES AND THEIR EXTENSIONS .Suo Solution User Option File .Vb Any File From Following

A Basic Window Form A Code File A Module File For Storing Functions A User Control As Data Form A Custom Control An Inherited Form A Web Custom Control An Inherited User Control A Window Services An Assembly Info File

.Xsd An Xml Schema Provided To Create Datasets .Htm An Html Document .Txt A Text File .Rpt Crystal Report .Bmp Bitmap File .Js Jscript File .Vbs Vbscript File .Wsf Windows Scripting File .Aspx A Web Form .Asp An Active Server Page .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

VB .NET IDE

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

Navgujarat BCA Page 7 of 98

Page 8: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

The Server Explorer The Output Window The Task List The Command Window Graphical Designers Form Designers Web Form Designers Component Designer Xml Designeres Code Designers

MODES OF VB .NET Design Time Mode Runtime Mode Break Time Mode

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. 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 Some Namespaces and their use:

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 sourcesSystem.Data.OleDb: Includes classes that support the OLEDB .NET provider

Navgujarat BCA Page 8 of 98

Page 9: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

System. Drawing: Provides access to drawing methods

System.IO: Includes classes for data access with Files

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

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. Assemblies take the form of a dynamic link library (.dll) file or executable program file (.exe) but they differ as they contain the information found in a type library and the information about everything else needed to use an application or component. All .NET programs are constructed from these Assemblies. 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. When programming, we don't directly deal with assemblies as the CLR and the .NET framework takes care of that behind the scenes. The assembly file is visible in the Solution Explorer window of the project.

Data Type SizeByte 1 8-bit System.ByteChar 2 16-bit System.CharInteger 4 32-bit System.Int32Double 8 64-bit System.DoubleLong 8 64-bit System.Int64Short 2 16-bit System.Int16Single 4 32-bit System.SingleString Varies Non-Numeric Type System.StringDate 8 System.DateBoolean 2 Non-Numeric Type System.BooleanObject 4 Non-Numeric Type System.ObjectDecimal 16 128-bit System.Decimal

Access Specifiers

Access specifiers let's us specify how a variable, method or a class can be used. The following are the most commonly used one's:

Public: Gives variable public access which means that there is no restriction on their accessibility Private: Gives variable private access which means that they are accessible only within their declaration content

Navgujarat BCA Page 9 of 98

Page 10: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Protected: Protected access gives a variable accessibility within their own class or a class derived from that class Friend: Gives variable friend access which means that they are accessible within the program that contains their declaration Protected Friend: Gives a variable both protected and friend 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 structureVariablesVariables 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. 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.

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. 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.

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.ConsoleModule Module1

Navgujarat BCA Page 10 of 98

Page 11: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Sub Main()Dim d As Doubled = 132.31223Dim i As Integeri = CType(d, i)'two arguments, type we are converting from, to type desiredWriteLine("Integer value is" & i)End SubEnd Module

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 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

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 DivisionMod Modulus Arithmetic+ Addition- Subtraction

Navgujarat BCA Page 11 of 98

Page 12: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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

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

Logical / Bitwise Operators The logical operators compare Boolean expressions and return a Boolean result. In short, logical operators are expressions which return a true or false result over a conditional expression. The table below summarizes them: Operator Use Not Negation And Conjunction AndAlso Conjunction Or Disjunction OrElse Disjunction Xor Disjunction

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. The following code demonstrates arrays. Module Module1Sub Main()Dim sport(5) As String

Navgujarat BCA Page 12 of 98

Page 13: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

'declaring an arraysport(0) = "Soccer"sport(1) = "Cricket"sport(2) = "Rugby"sport(3) = "Aussie Rules"sport(4) = "BasketBall"sport(5) = "Hockey"'storing values in the arrayWriteLine("Name of the Sport in the third location" & " " & sport(2))'displaying value from arrayEnd SubEnd Module

STRING FUNCTIONS

Public Function Asc(ByVal String As Char) As Integer Member of: Microsoft.VisualBasic.StringsSummary:Returns an Integer representing the character code corresponding to the first letter in a string. Public Function Chr(ByVal CharCode As Integer) As Char Member of: Microsoft.VisualBasic.StringsSummary:Returns the character associated with the specified character code as a Char data type. Public Function Format(ByVal Expression As Object, Optional ByVal Style As String = "") As String Member of: Microsoft.VisualBasic.StringsSummary:Returns a String expression formatted according to instructions contained in a format String expression. STRING FUNCTIONS Public Function Mid(ByVal str As String, ByVal Start As Integer) As String Member of: Microsoft.VisualBasic.Strings

Summary:Replaces a specified number of characters in a String variable with characters from another string.

Parameters:str: Name of the String variable to modify. Start: Integer data type. Character position in target where the replacement of text begins. Start uses a one based index.

Navgujarat BCA Page 13 of 98

Page 14: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Public Function StrComp(ByVal String1 As String, ByVal String2 As String, Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = 0) As Integer Member of: Microsoft.VisualBasic.Strings

Summary:Returns -1, 0, or 1, based on the result of a string comparison. The strings are compared by alphanumeric sort values begining with the first character.

Parameters:String1: Any valid String expression. String2: Any valid String expression. Compare: Specifies the type of string comparison. If compare is omitted, the Option Compare setting determines the type of comparison.

Public Function GetChar(ByVal str As String, ByVal Index As Integer) As Char Member of: Microsoft.VisualBasic.StringsSummary:Returns the character at a specified position in a stringParameters:str: String to use as a sourceIndex: 1 based index of the character to return Public Function InStr(ByVal Start As Integer, ByVal String1 As String, ByVal String2 As String, Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = 0) As Integer Member of: Microsoft.VisualBasic.StringsSummary:Returns an Integer specifying the start position of the first occurrence of one string within another. Parameters:Start: Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. The start index is 1 based. String1: String expression being searched. String2: String expression sought.

Public Function InStrRev(ByVal StringCheck As String, ByVal StringMatch As String, Optional ByVal Start As Integer = -1, Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = 0) As Integer Member of: Microsoft.VisualBasic.StringsSummary:Returns the position of the first occurrence of one string within another, starting from the right side of the string. Parameters:StringCheck: String expression being searched. StringMatch: String expression being searched for.

Navgujarat BCA Page 14 of 98

Page 15: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Start: Numeric expression that sets the one-based starting position for each search, starting from the left side of the string. If Start is omitted, –1 is used, which means that the search begins at the last character position. Search then proceeds from right to left. Public Function Join(ByVal SourceArray() As Object, Optional ByVal Delimiter As String = " ") As String Member of: Microsoft.VisualBasic.StringsSummary:Returns a string created by joining a number of substrings contained in an array. Parameters:SourceArray: One-dimensional array containing substrings to be joined. Delimiter: String used to separate the substrings in the returned string. If omitted, the space character (" ") is used. If Delimiter is a zero-length string (""), all items in the list are concatenated with no delimiters. Public Function LCase(ByVal Value As String) As String Member of: Microsoft.VisualBasic.Strings

Summary:Returns a String or Char that has been converted to lowercase. Parameters:Value: Any valid String or Char expression. Public Function Left(ByVal str As String, ByVal Length As Integer) As String Member of: Microsoft.VisualBasic.StringsSummary:Returns a String containing a specified number of characters from the left side of a string. Parameters:Str: String expression from which the leftmost characters are returned. Length: Integer expression. Numeric expression indicating how many characters to return. If 0, a zero-length string ("") is returned. If greater than or equal to the number of characters in Str, the entire string is returned. Public Function Len(ByVal Expression As Byte) As Integer Member of: Microsoft.VisualBasic.Strings Summary: Returns an Integer containing either the number of characters in a string or the number of bytes required to store a variable. Parameters: Expression: valid String expression or variable name. If Expression is of type Object, the Len function returns the size as it will be written to the file. Public Function Mid(ByVal str As String, ByVal Start As Integer) As String Member of: Microsoft.VisualBasic.StringsSummary:Replaces a specified number of characters in a String variable with characters from another string. Parameters:str: Name of the String variable to modify. Start: Integer data type. Character position in target where the replacement of text begins. Start uses a one based index.

Navgujarat BCA Page 15 of 98

Page 16: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Public Function Replace(ByVal Expression As String, ByVal Find As String, ByVal Replacement As String, Optional ByVal Start As Integer = 1, Optional ByVal Count As Integer = -1, Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = 0) As String Member of: Microsoft.VisualBasic.StringsSummary:Returns a string in which a specified substring has been replaced with another substring a specified number of times. Parameters:Expression: String expression containing substring to replace. Find: Substring being searched for. Replacement: Replacement substring. Start: Position within Expression where substring search is to begin. If omitted, 1 is assumed. Count: Number of substring substitutions to perform. If omitted, the default value is –1, which means make all possible substitutions. Compare: Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings for values. Public Function Split(ByVal Expression As String, Optional ByVal Delimiter As String = " ", Optional ByVal Limit As Integer = -1, Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = 0) As String() Member of: Microsoft.VisualBasic.StringsSummary:Returns a zero-based, one-dimensional array containing a specified number of substrings. Parameters:Expression: String expression containing substrings and delimiters. If Expression is a zero-length string (""), the Split function returns an array with no elements and no data. Delimiter: Single character used to identify substring limits. If Delimiter is omitted, the space character (" ") is assumed to be the delimiter. If Delimiter is a zero-length string, a single-element array containing the entire Expression string is returned. Limit: Number of substrings to be returned; the default, –1, indicates that all substrings are returned. Compare: Numeric value indicating the comparison to use when evaluating substrings. See Settings for values. CONTROL STATEMENTS IF condition THENELSEIF condition THENELSEEND IF

Navgujarat BCA Page 16 of 98

Page 17: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

SELECT CASE exprCASE exprlst1CASE exprlst2….….CASE exprlstNEND SELECT

SWITCH(expr-1,value-1,expr-2, value-2,..expr-N, value-N)

CHOOSE(index,chice-1, chice-2, chice-3…. chice-N)LOOPING CONSTUCTS

DO while/until conditionStmtExit do LOOP for index=start to end stepStatementsExit forNEXT

WHILE conditionStatementsWEND

WITH objectStatementsEND WITH

Messagebox Function

MessageBox.Show(Arguments) Several choices for argument list Introduces concept of Overloaded functions Multiple signatures to choose fromMessageBox.Show(TextMessage)MessageBox.Show(TextMessage, TitlebarText)MessageBox.Show(TextMessage, TitlebarText, _

MessageBoxButtons)MessageBox.Show(TextMessage, TitlebarText, _

MessageBoxButtons, MessageBoxIcon)

MessageBox Icons and buttons Enumeration of constants

Navgujarat BCA Page 17 of 98

Page 18: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Menus,Sub Procedures,Sub Functions Creating Menus and Menu Items Creating ContextMenus Displaying Common Dialog Boxes Writing General Procedures

Menus Create a menu by adding a MainMenu control to the component tray Great new Menu Designer replaces the Menu Editor

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

Sub Function

Arguments are passed ByVal (by default) The Editor adds ByVal if you leave it out 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'Calculate the sum of the numbers

Return intNum1 + intNum2End Function

CONTROLS

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. Button Event

Navgujarat BCA Page 18 of 98

Page 19: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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 clickedEnd Sub Important Properties of Button1 Appearance BackColor and Background Image properties we can set a 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. Behavior Notable Behavior properties of the Button are the 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. 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. Creating a Button in Code Public Class Form1 Inherits System.Windows.Forms.FormPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e_As System.EventArgs) Handles_ MyBase.LoadDim Button1 as New Button()'declaring the button, Button1Button1.Text="Creating a Button"'setting the text to be displayed on the ButtonButton1.Location=New Point(100,50)'setting the location for the Button where it should be createdButton1.Size=New Size(75,23)'setting the size of the ButtonMe.Controls.Add(Button1)'adding the Button that is created to the form

Navgujarat BCA Page 19 of 98

Page 20: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

'the Me keyword is used to refer to the current object, in this case the FormEnd SubEnd Class

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. Creating a Label in Code Private Sub Form1_Load(ByVal sender As 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

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 Some Notable Properties: Behavior Enabled: Default value is True. To disable, set the 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 *.Read Only: 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

Appearance section TextAlign: Allows to align the text from three 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. Code to Validate User Input We can make sure that a TextBox can accept only characters or numbers which can

Navgujarat BCA Page 20 of 98

Page 21: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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.KeyPressIf(e.KeyChar < "10" Or e.KeyChar > "100") ThenMessageBox.Show("Enter Double Digits")End IfEnd Sub Creating a TextBox in Code Public Class Form1 Inherits System.Windows.Forms.FormPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As_System.EventArgs) Handles MyBase.LoadDim 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 SubEnd Class

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.

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.

Navgujarat BCA Page 21 of 98

Page 22: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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. Code to check a CheckBox's state Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_System.EventArgs) Handles Button1.ClickIf CheckBox1.Checked = True ThenTextBox1.Text = "Checked"ElseTextBox1.Text = "UnChecked"End IfEnd Sub Creating a CheckBox in Code Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_System.EventArgs) Handles_ MyBase.LoadDim 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

ComboBox ComboBox is a combination of a TextBox and a ListBox. The ComboBox displays an editing field (TextBox) combined with a ListBox allowing us to select from the list or to enter new text. ComboBox displays data in a drop-down style format. The ComboBox class is derived from the ListBox class. Below is the Image of a ComboBox.

Notable properties of the ComboBox The DropDownStyle property in the Appearance section of the 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.

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:

Navgujarat BCA Page 22 of 98

Page 23: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_System.EventArgs) Handles Button1.ClickComboBox1.Items.RemoveAt(4)'removing an item by specifying it's indexEnd Sub

Code to remove all items from the ComboBox Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_System.EventArgs) Handles Button1.ClickComboBox1.Items.Clear()'using the clear method to clear the list boxEnd Sub

Handling Mouse Events in Forms 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 pressedMouseEnter: This event happens when the mouse pointer enters the form/controlMouseUp: This event happens when the mouse pointer is over the form/control and the mouse button is releasedMouseLeave: This event happens when the mouse pointer leaves the form/controlMouseMove: This event happens when the mouse pointer is moved over the form/controlMouseWheel: This event happens when the mouse wheel moves while the form/control has focusMouseHover: 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 pressedClicks: Specifies number of times the mouse button is pressed and releasedX: The X-coordinate of the mouse clickY: The Y-coordinate of the mouse clickDelta: Specifies a count of the number of detents (rotation of mouse wheel) the mouse wheel has rotated

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.

Notable Properties of the ListBox In the Behavior Section

Navgujarat BCA Page 23 of 98

Page 24: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

HorizontalScrollbar: Displays a horizontal scrollbar to the 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.

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.ClickTextBox1.Text = ListBox1.Items.Count'counting the number of items in the ListBox with the Items.CountEnd 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.SelectedIndexChangedTextBox1.Text = ListBox1.SelectedItem'using the selected item propertyEnd Sub When you run the code and click an item in the

Code to remove a particular item Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _As System.EventArgs) Handles Button1.ClickListBox1.Items.RemoveAt(4)'removing an item by specifying it's indexEnd Sub Code to Remove all items Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickListBox1.Items.Clear()'using the clear method to clear the list boxEnd Sub ExampleCode to add and remove dataCode to Shift single selected item from one listbox to another listboxCode to shift multiple itemsExample-checkbox and option button

Navgujarat BCA Page 24 of 98

Page 25: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Example-CalculatorCode for number buttonsCode for Operators buttonsCode for equals buttons

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.

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.

SaveFileDialog Save File Dialog's are supported by the SaveFileDialog class and they allow us to save the file in a specified location.

Navgujarat BCA Page 25 of 98

Page 26: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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.

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.

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.

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.

Navgujarat BCA Page 26 of 98

Page 27: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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. The key properties of the TreeView control are Nodes and SelectedNode. The Nodes property contains the list of top-level nodes in the tree view. The SelectedNode property sets the currently selected node. Icons can be displayed next to the nodes; the images are taken from the ImageList control named in the tree view's ImageList property. The ImageIndex property sets the default image for nodes in the tree view. For more information on displaying images

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.

The TreeNode Editor appears.

3. 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.

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)

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.SelectedNode)TreeView1.Nodes.Clear()

To determine which TreeView node was clicked

Use the EventArgs object to return a reference to the clicked node object. Determine which node was clicked by checking the TreeViewEventArgs class, which contains data related to the event.

Navgujarat BCA Page 27 of 98

Page 28: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, _ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect . MessageBox.Show(e.Node.Text)End Sub

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 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.

The key property of the ListView control is Items, which 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

To add or remove items in the designer

1. In the Properties window, click the ellipsis button ( ) next to the Items property.

Navgujarat BCA Page 28 of 98

Page 29: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

The ListViewItem Collection Editor appears.

2. 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.

To add items programmatically

ListView1.Items.Add("List item text", 3)

To add columns in the designer

1. Set the control's View property to Details.

2. In the Properties window, click the ellipsis button ( ) next to the Columns property.

The ColumnHeader Collection Editor appears.

3. 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.

To add columns programmatically

Set the control's View property to Details.

Use the Add method of the list view's Columns property.

ListView1.View = View.DetailsListView1.Columns.Add("File type", 20, HorizontalAlignment.Left)

To display images in a list view

1. Set the appropriate property, SmallImageList, LargeImageList, or StateImageList, to the existing ImageList component you wish to use.

These properties can be set in the designer with the Properties window, or in code.

' Visual BasicListView1.SmallImageList = ImageList1

2. Set the ImageIndex or StateImageIndex property for each list item that has an associated icon.

Navgujarat BCA Page 29 of 98

Page 30: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

These properties can be set in code, or within the ListViewItem Collection Editor. To open the ListViewItem Collection Editor, click the ellipsis button (

) next to the Items property on the Properties window.

' Visual Basic' Sets the first list item to display the 4th imageListView1.Items(0).ImageIndex = 3

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.

OOP-Terminology

EncapsulationInheritancePolymorphism

CLASSES

Instantiating an objectNew class namei.e Dim c = new font(“arial”,12)Lblfnt.font=c

Creating your own classes

Create a new application of type class libraryCreate properties of the class.Property procedurethe 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 IntegerGet

Navgujarat BCA Page 30 of 98

Page 31: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

op1 = no1End GetSet(ByVal Value As Integer)no1 = ValueEnd SetEnd Property

Creating your own classes

Create a new application of type class libraryCreate properties of the class.Property procedurethe 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 IntegerGetop1 = no1End GetSet(ByVal Value As Integer)no1 = ValueEnd SetEnd Property

Creating new object using classes

Create new object using following statement in windows applicationDim c as new class nameThis class name must be add as a reference in a project.

Data Access Technologies

Most applications require some form of data access. If you are creating a new application, you have three excellent data access choices: ADO.NET, ADO, and OLE DB. If you need to modify the data access for an existing application, you might continue using the application's current data access technology for maintenance convenience. However, if you expect the application to have a long lifecycle, you should consider reengineering to use either ADO.NET for managed applications or ADO for native applications. In the long run, the newer data access technologies typically reduce development time, simplify code, and provide excellent performance.

Navgujarat BCA Page 31 of 98

Page 32: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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.

ADO.NET is designed specifically for message-based Web applications while still providing preferable functionality for other application architectures. By supporting loosely coupled access to data, ADO.NET maximizes data sharing by reducing the number of active connections to the database — reducing the possibility of multiple users contending for limited resources on the database server.

ADO.NET provides several ways to access data. If your Web application or XML Web service requires data access from multiple sources, needs to interoperate with other applications (both local and remote), or can benefit from persisting and transmitting cached results, the dataset is an excellent choice. As an alternative, ADO.NET provides data commands and data readers to communicate directly with the data source. Direct database operations using data commands and data readers include running queries and stored procedures, creating

Advantages of ADO.NET over ADO

Interoperability

ADO.NET applications can take advantage of the flexibility and broad acceptance of XML. Because XML is the format for transmitting datasets across the network, any component that can read the XML format can process data. In fact, the receiving component need not be an ADO.NET component at all: The transmitting component can simply transmit the dataset to its destination without regard to how the receiving component is implemented. The destination component might be a Visual Studio application or any other application implemented with any tool whatsoever. The only requirement is that the receiving component be able to read XML. As an industry standard, XML was designed with exactly this kind of interoperability in mind.

Maintainability

Navgujarat BCA Page 32 of 98

Page 33: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

In the life of a deployed system, modest changes are possible, but substantial, architectural changes are rarely attempted because they are so difficult. That is unfortunate, because in a natural course of events, such substantial changes can become necessary. For example, as a deployed application becomes popular with users, the increased performance load might require architectural changes. As the performance load on a deployed application server grows, system resources can become scarce and response time or throughput can suffer. Faced with this problem, software architects can choose to divide the server's business-logic processing and user-interface processing onto separate tiers on separate machines. In effect, the application server tier is replaced with two tiers, alleviating the shortage of system resources.

The problem is not designing a three-tiered application. Rather, it is increasing the number of tiers after an application is deployed. If the original application is implemented in ADO.NET using datasets, this transformation is made easier. Remember, when you replace a single tier with two tiers, you arrange for those two tiers to trade information. Because the tiers can transmit data through XML-formatted datasets, the communication is relatively easy.

Programmability

ADO.NET data components in Visual Studio encapsulate data access functionality in various ways that help you program more quickly and with fewer mistakes. For example, data commands abstract the task of building and executing SQL statements or stored procedures.Similarly, ADO.NET data classes generated by the tools result in typed datasets. This in turn allows you to access data through typed programming. For example, consider the following line of code that accesses a data member in an untyped dataset:The equivalent line to access a data member in a typed dataset looks like the following:' Visual Basic

Performance

For disconnected applications, ADO.NET datasets offer performance advantages over ADO disconnected recordsets. When using COM marshalling to transmit a disconnected recordset among tiers, a significant processing cost can result from converting the values in the recordset to data types recognized by COM. In ADO.NET, such data-type conversion is not necessary.

Scalability

Because the Web can vastly increase the demands on your data, scalability has become critical. Internet applications have a limitless supply of potential users. Although an application might serve a dozen users well, it might not serve hundreds —or hundreds of thousands — equally well. An application that consumes resources such as database

Navgujarat BCA Page 33 of 98

Page 34: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

locks and database connections will not serve high numbers of users well, because the user demand for those limited resources will eventually exceed their supply.

In-memory Representations of Data

In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. There are important differences between them.

Data Navigation and Cursors

In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases.

A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. For more information about cursor functionality, see Data Access Technologies.

Choosing ADO.NET or ADO

Both ADO.NET and ADO are easy to program, language-independent, implemented with a small footprint, use minimal network traffic, and require few layers between the application's front-end and the data source. Both methods provide high-performance data access.

Choosing either of these data access technologies affects an application's design, extensibility, interoperability, ease of maintenance, and many other factors. These include:

Managed code   If your application is written in managed code and built upon the common language runtime, you should use ADO.NET. If you are writing unmanaged code in C++ (and especially if you are maintaining an existing ADO application), ADO is still a good choice.

Data structure   The ADO.NET dataset can contain one or more tables, and provides both a table-based relational view and an XML-based view. The dataset uses standard common language runtime types, which simplifies programming.

The ADO recordset is a single table, accessible only as a recordset, and does not contain relationships. An ADO recordset can be the result of a multiple table

Navgujarat BCA Page 34 of 98

Page 35: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

JOIN query, but it is still only a single result table. If you want multiple tables with ADO, you must have multiple Recordset objects. The ADO.NET dataset provides better functionality due to its integrated relational structure.

Data sharing   ADO.NET provides the basis for data interchange between components and across tiers: datasets can be passed over the Internet and through firewalls as XML. You can view the same set of data as relational tables within your application and as an XML data structure in some other application. The dataset provides convenient two-way transformation: from dataset tables to an XML document, and from an XML document into dataset tables.

If you use COM marshaling to transmit an ADO recordset, the target application must be programmed to use the recordset data structure. This requires more difficult programming than simply reading XML data. Alternatively, you can persist the ADO recordset as XML and more easily share the data with other applications and services.

Scalability   ADO.NET is the most scalable solution. ADO.NET is designed from the ground up to be the best data access architecture for building scalable Web applications with a low total cost of ownership. If you do not need the scalability, and are not writing in managed code, you can continue to use ADO.

Cursor location   An application can establish result sets in either of two places: within the application process (client-side cursor) or within the data store process (server-side cursor). Client-side cursors are generally a good choice for any type of impromptu user interaction with the data. Client-side cursors are supported in ADO.NET by the DataSet object and in ADO by the ClientCursor Recordset object.

Introduction to Data Access with ADO.NET

As you develop applications using ADO.NET, you will have different requirements for working with data. In some cases, you might simply want to display data on a form. In other cases, you might need to devise a way to share information with another company.

No matter what you do with data, there are certain fundamental concepts that you should understand about the data approach in ADO.NET. You might never need to know some of the details of data handling — for example, you might never need to directly edit an XML file containing data — but it is very useful to understand the data architecture in ADO.NET, what the major data components are, and how the pieces fit together.

This introduction presents a high-level overview of these most important concepts. The topic deliberately skips over many details — for example, there is much more to datasets than what is mentioned here — in favor of simply introducing you to ideas behind data integration in ADO.NET.

Navgujarat BCA Page 35 of 98

Page 36: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

ADO.NET Does Not Depend On Continuously Live Connections

In traditional client/server applications, components establish a connection to a database and keep it open while the application is running. For a variety of reasons, this approach is impractical in many applications:

Open database connections take up valuable system resources. In most cases, databases can maintain only a small number of concurrent connections. The overhead of maintaining these connections detracts from overall application performance.

Similarly, applications that require an open database connection are extremely difficult to scale up. An application that does not scale up well might perform acceptably with four users but will likely not do so with hundreds. ASP.NET Web applications in particular need to be easily scalable, because traffic to a Web site can go up by orders of magnitude in a very short period.

In ASP.NET Web applications, the components are inherently disconnected from each other. The browser requests a page from the server; when the server has finished processing and sending the page, it has no further connection with the browser until the next request. Under these circumstances, maintaining open connections to a database is not viable, because there is no way to know whether the data consumer (the client) requires further data access.

A model based on always-connected data can make it difficult and impractical to exchange data across application and organizational boundaries using a connected architecture. If two components need to share the same data, both have to be connected, or a way must be devised for the components to pass data back and forth.

Database Interactions Are Performed Using Data Commands

To perform operations in a database, you execute SQL statements or stored procedures (which include SQL statements). You use SQL statements or stored procedures to read and write rows and perform aggregate functions, such as adding or averaging. You also use SQL statements or stored procedures to create or modify tables or columns, to perform transactions, and so on.

In ADO.NET you use data commands to package a SQL statement or stored procedure. For example, if you want to read a set of rows from the database, you create a data command and configure it with the text of a SQL Select statement or the name of a stored procedure that fetches records.

When you want to get the rows, you do the following:

1. Open a connection. 2. Call an execute method of the command, which in turn:

a. Executes the SQL statement or stored procedure referenced by the command.

Navgujarat BCA Page 36 of 98

Page 37: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

b. Then closes the connection.

The connection stays open only long enough to execute the statement or stored procedure.

When you call a command's execute method, it returns a value. Commands that update the database return the number of rows affected; other types of commands return an error code. If the command queries the database with a SELECT statement, the command can return a set of rows. You can fetch these rows using a data reader, which acts as a very fast read-only, forward-only cursor. For more information, see Retrieving Data Using the DataReader.

Components of ADO.NET

The following illustration shows the major components of an ADO.NET application.

ADO.NET Data Components

The following table summarizes the ADO.NET data components illustrated above and provides links to more information.

Component or objectDatasetData adapterData connectionWindows FormWeb Forms pageBizTalk

ADO.NET Connection

To move data between a data store and your application, you must first have a connection to the data store.

Note   Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio. For more information, see .NET Data Providers.

In ADO.NET you create and manage connections using connection objects:

Navgujarat BCA Page 37 of 98

Page 38: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

SqlConnection - an object that manages a connection to a SQL Server version 7.0 or later. It is optimized for use with SQL Server 7.0 or later by (among other things) bypassing the OLE DB layer.

OleDbConnection - an object that manages a connection to any data store accessible via OLE DB.

OdbcConnection - an object that manages a connection to a data source created by using a connection string or ODBC data source name (DSN).

OracleConnection - an object that manages a connection to Oracle databases.

Connection Strings

All connection objects expose roughly the same members. However, the specific members available with a given OleDbConnection object depend on what data source it is connected to; not all data sources support all members of the OleDbConnection class.

The primary property associated with a connection object is the ConnectionString property, which consists of a string with attribute/value pairs for information required to log on to a database and point to a specific database. A typical ConnectionString property might look like the following:

Provider=SQLOLEDB.1;Data Source=MySQLServer;Initial Catalog=NORTHWIND;Integrated Security=SSPI

The most common attribute/value pairs used by OLE DB are also represented separately by an individual property, such as DataSource and Database. When working with a connection object, you can either set the ConnectionString property as a single string, or you can set individual connection properties. (If your data source requires connection-string values that are not represented by individual properties, then you must set the ConnectionString property.) Alternatively, you can also set the ConnectionString property to the path of a Microsoft Data Link (.udl) file. For more information about data link files, see Data Link API Overview.

Opening and Closing Connections

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.

Navgujarat BCA Page 38 of 98

Page 39: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Design-Time Connections in Server Explorer

Server Explorer provides a way for you to create design-time connections to data sources. This permits you to browse available data sources; display information about the tables, columns, and other elements they contain; and edit and create database elements.

Your application does not directly use the connections you create this way. Generally, the information provided by a design-time connection is used to set properties for a new connection object that you add to your application.

Connection Design Tools in Visual Studio

You usually do not need to directly create and manage connection objects in Visual Studio. When you use tools such as the Data Adapter Wizard, the tools typically prompt you for connection information (that is, connection-string information) and automatically create connection objects for you on the form or component you are working with.

However, if you want, you can add connection objects yourself to a form or component and set their properties. This is useful if you are not working with datasets (and therefore not with data adapters), but instead simply reading data. You might create connection objects yourself if you will be using transactions.

Introduction to Data Adapters

Data adapters are an integral part of ADO.NET managed providers, which are the set of objects used to communicate between a data source and a dataset. (In addition to adapters, managed providers include connection objects, data reader objects, and command objects.) Adapters are used to exchange data between a data source and a dataset. In many applications, this means reading data from a database into a dataset, and then writing changed data from the dataset back to the database. However, a data adapter can move data between any source and a dataset. For example, there could be an adapter that moves data between a Microsoft Exchange server and a dataset.

Generally, adapters are configurable to allow you to specify what data to move into and out of the dataset. Often this takes the form of references to SQL statements or stored procedures that are invoked to read or write to a database.

Visual Studio makes these data adapters available for use with databases:

The OleDbDataAdapter object is suitable for use with any data source exposed by an OLE DB provider.

The SqlDataAdapter object is specific to SQL Server. Because it does not have to go through an OLE DB layer, it is faster than the OleDbDataAdapter. However, it can only be used with SQL Server 7.0 or later.

The OdbcDataAdapter object is optimized for accessing ODBC data sources.

Navgujarat BCA Page 39 of 98

Page 40: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

The OracleDataAdapter object is optimized for accessing Oracle databases.

Data Adapters and Related Tables

An implication of having separate tables in the dataset is that a data adapter typically does not reference SQL commands or stored procedures that join tables. Instead, information from the related tables is read separately into the dataset by different adapters. Then a DataRelation object is used to manage constraints between the dataset tables (such as cascading updates) and to allow you to navigate between related master and child records.

For example, imagine that you are working with two related tables in the Northwind database, Customers and Orders. Rather than specifying a join to combine both tables into a single result set, you would most commonly define two adapters, one to populate a Customers table in the dataset and a second adapter to read Order records into a different dataset table. The individual adapters would probably include selection criteria to limit the number of records in the data tables.

In the dataset you would also define a DataRelation object specifying that order records are related to customer records by the CustomerID field. You can still manage the tables individually, which would not be possible if you had joined tables before fetching records from the data source. For situations where you wanted to work with related records, you can invoke properties and methods of the DataRelation object.

ADO.NET Command Objects

Using an adapter, you can read, add, update, and delete records in a data source. To allow you to specify how each of these operations should occur, an adapter supports the following four properties:

SelectCommand – reference to a command (SQL statement or stored procedure name) that retrieves rows from the data store.

InsertCommand – reference to a command for inserting rows into the data store. UpdateCommand – reference to a command for modifying rows in the data

store. DeleteCommand – reference to a command for deleting rows from the data store.

The properties are themselves objects — they are instances of the SqlCommand, OleDbCommand, OdbcCommand, or OracleCommand class. The objects support a CommandText property containing a reference to an SQL statement or stored procedure.

Navgujarat BCA Page 40 of 98

Page 41: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Note   The command class must match the connection class. For example, if you are using a SqlConnection object to communicate with a SQL Server, you must also use commands that derive from the SqlCommand class.

Although you can explicitly set the text of a command object, you do not always need to; in many situations, Visual Studio will generate the SQL statements needed. In addition, the adapter can automatically generate appropriate SQL statements at run time if the UpdateCommand, InsertCommand, or DeleteCommand objects are not specified. For details, see Automatically Generated Commands.

However, you can manipulate command objects at design time and run time in order to have more direct control over how the commands are executed. For example, you can create or modify the command associated with a SelectCommand object just before it is executed.

You can also execute commands yourself, independently of the data adapter. This allows you to pass arbitrary SQL commands through the data adapter, such as those used to define or modify database definitions. You can also call stored procedures directly that do not return record sets — for example, a stored procedure that validates a user entry

Command Parameters

The commands in a data adapter are usually parameter-driven. The command for the SelectCommand property, for example, often has a parameter in its WHERE clause so you can specify at run time what records to get from the database. The other commands use parameters that allow you to pass at run time the data to write into a record and what record in the database to update. For more information about how parameters are used in data adapters, see Parameters in Data-Adapter Commands.

Reading and Updating with Data Adapters

The primary purpose of the data adapter is to communicate data between a data store and a dataset. The adapter supports specific methods to move the data back and forth between the two.

Note   If you just want to read data (not update it), you do not have to store it in a dataset. Instead, you can read directly out of the database and into an application. For details, see "Read-Only Data" below.

You can use a data adapter to perform the following operations:

Retrieve rows from a data store into corresponding data tables within the dataset.

To retrieve rows into a dataset, use the Fill method on a data adapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter, or OracleDataAdapter).

Navgujarat BCA Page 41 of 98

Page 42: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

When you invoke the Fill method, it transmits an SQL SELECT statement to the data store.

Transmit changes made to a dataset table to the corresponding data store.

ADO.NET Datasets

Datasets are containers — caches — in which you can store data to use in your application. Datasets are a fundamental part of the ADO.NET architecture, providing both high-performance data access as well as scalability.

Datasets store data in a disconnected cache. The structure of a dataset is similar to that of a relational database; it exposes a hierarchical object model of tables, rows, and columns. In addition, it contains constraints and relationships defined for the dataset.

The fundamental parts of a dataset are exposed to you through standard programming constructs such as properties and collections. For example:

The DataSet class includes the Tables collection of data tables and the Relations collection of DataRelation objects.

The DataTable class includes the Rows collection of table rows, the Columns collection of data columns, and the ChildRelations and ParentRelations collections of data relations.

The DataRow class includes the RowState property, whose values indicate whether and how the row has been changed since the data table was first loaded from the database. Possible values for the RowState property include Deleted, Modified, New, and Unchanged.

Typed versus Untyped Datasets

Datasets can be typed or untyped. A typed dataset is a dataset that is first derived from the base DataSet class and then uses information in an XML Schema file (an .xsd file) to generate a new class. Information from the schema (tables, columns, and so on) is generated and compiled into this new dataset class as a set of first-class objects and properties.

Because a typed DataSet class inherits from the base DataSet class, the typed class assumes all of the functionality of the DataSet class and can be used with methods that take an instance of a DataSet class as a parameter

An untyped dataset, in contrast, has no corresponding built-in schema. As in a typed dataset, an untyped dataset contains tables, columns, and so on — but those are exposed only as collections. (However, after manually creating the tables and other data elements

Navgujarat BCA Page 42 of 98

Page 43: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

in an untyped dataset, you can export the dataset's structure as a schema using the dataset's WriteXmlSchema method.)

You can use either type of dataset in your applications. However, Visual Studio has more tool support for typed datasets, and they make programming with the dataset easier and less error-prone.

Populating Datasets

A dataset is a container; therefore, you need to fill it with data. When you populate a dataset, various events are raised, constraint checking applies, and so on. For more information about updating a dataset and the issues surrounding updates

You can populate a dataset in a variety of ways:

Call the Fill method of a data adapter. This causes the adapter to execute an SQL statement or stored procedure and fill the results into a table in the dataset. If the dataset contains multiple tables, you probably have separate data adapters for each table, and must therefore call each adapter's Fill method separately.

Manually populate tables in the dataset by creating DataRow objects and adding them to the table's Rows collection. (You can only do this at run time; you cannot set the Rows collection at design time.) For more information, see Adding Data to a Table.

Read an XML document or stream into the dataset. For more information, see the ReadXml method.

Updating Datasets and Data Stores

When changes are made to records in the dataset, the changes have to be written back to the database. To write changes from the dataset to the database, you call the Update method of the data adapter that communicates between the dataset and its corresponding data source.

The DataRow class used to manipulate individual records includes the RowState property, whose values indicate whether and how the row has been changed since the data table was first loaded from the database. Possible values include Deleted, Modified, New, and Unchanged. The Update method examines the value of the RowState property to determine which records need to be written to the database and what specific database command (add, edit, delete) should be invoked.

DataReader

You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Results are returned as the query executes, and are stored in the network buffer on the client until you request them using the Read method of the

Navgujarat BCA Page 43 of 98

Page 44: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

DataReader. Using the DataReader can increase application performance both by retrieving data as soon as it is available, rather than waiting for the entire results of the query to be returned, and (by default) storing only one row at a time in memory, reducing system overhead.

After creating an instance of the Command object, you create a DataReader by calling Command.ExecuteReader to retrieve rows from a data source, as shown in the following example.

[Visual Basic]

Dim myReader As SqlDataReader = myCommand.ExecuteReader()

You use the Read method of the DataReader object to obtain a row from the results of the query. You can access each column of the returned row by passing the name or ordinal reference of the column to the DataReader. However, for best performance, the DataReader provides a series of methods that allow you to access column values in their native data types (GetDateTime, GetDouble, GetGuid, GetInt32, and so on). For a list of typed accessor methods

Closing the DataReader

You should always call the Close method when you have finished using the DataReader object.

If your Command contains output parameters or return values, they will not be available until the DataReader is closed.

Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You will not be able to execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.

Navgujarat BCA Page 44 of 98

Page 45: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

ERROR HANDLING

Types of Errors

In Visual Basic, errors (also called exceptions) fall into one of three categories: syntax errors, run-time errors, and logic errors.

Syntax Errors

Syntax errors are those that appear while you write your code. Visual Basic checks your code as you type and alerts you if you make a mistake, such as misspelling a word or using a language element improperly. Syntax errors are the most common type of errors. You can fix them easily in the coding environment as soon as they occur.

Note   The Option Explicit statement is one means of avoiding syntax errors. It forces the programmer to declare, in advance, all the variables to be used in the application. Therefore, when those variables are used in the code, any typographic errors are caught immediately and can be fixed.

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 run-time 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.

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. You can test and respond to trappable errors using

Navgujarat BCA Page 45 of 98

Page 46: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

the On Error statement and the Err object's Number property. Unused error numbers in the range 1 to 1000 are reserved for future use by Visual Basic.

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.

The errors that Visual Basic .NET throws are Error objects. Visual Basic .NET can generate custom errors of any data type, including Error objects, by using the Throw statement. A program can display the error number and message of a caught Error to identify the error. If an error is not caught, the program ends.

Run-time errors can be trapped and examined by the code. By enclosing the code that produces the error in a Try block, any thrown error can be caught within a matching Catch block.

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.

Debugging

As you’ve seen, encountering errors is nearly a certainty when developing a piece of software. Syntaxerrors, of course, are the easiest to detect, because the IDE tells you right where they are and whatthe nature of the error is. It’s the runtime errors that are harder to locate and correct, because of themany forms these errors can take. You’ve seen examples of errors that will cause your program tocrash, as well as errors that spiral your program off into an infinite loop, and even errors that produceno outward signs at all—they simply cause the program to behave in some unintended way.Fortunately, Visual Studio .NET provides you with a fine selection of tools to detect and removethe errors in your program. The act of hunting and eliminating errors is called debugging, becauseyou’re goal is to remove the bugs (or de-bug) the program.

Navgujarat BCA Page 46 of 98

Page 47: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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 informatio.

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

Try...Catch...Finally Statements

Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.Try [ tryStatements ][ Catch [ exception [ As type ] ] [ When expression ] [ catchStatements ] ][ Exit Try ]...[ Finally [ finallyStatements ] ]End Try

PartstryStatements

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

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.

Navgujarat BCA Page 47 of 98

Page 48: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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.

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.

The Try block contains code where an error can occur, while the Catch block contains code to handle any error that does occur. If an error occurs in the Try block, program control is passed to the appropriate Catch statement for disposition. The exception argument is an instance of the Exception class or an instance of a class that derives from the Exception class corresponding to the error that occurred in the Try block. The Exception class instance contains information about the error including, among other things, its number and message.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _System.EventArgs) Handles Button1.Clickdim A AS integer Try A=”SYBCA” Catch ex As Exception MsgBox("Can't assign value string to integer" ) End TryEnd Sub

Example

The following simplified example illustrates the structure of the Try...Catch...Finally statement:

Navgujarat BCA Page 48 of 98

Page 49: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Public Sub TryExample() Dim x As Integer = 5 ' Declare variables. Dim y As Integer = 0 Try ' Set up structured error handling. x /= y ' Cause a "Divide by Zero" error. Catch ex As Exception When y = 0 ' Catch the error. MsgBox(ex.toString) ' Show friendly error message. Finally Beep() ' Beep after error processing. End TryEnd Sub

ArrayList Collection Type

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. For example:

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.

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.

ArrayList provides methods that return read-only and fixed-size wrappers to the collection. Array does not.

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.

Navgujarat BCA Page 49 of 98

Page 50: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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.

Most situations that call for an array can use ArrayList instead. It is easier to use and, in general, has performance similar to an array of type Object.

Array is in the System namespace; ArrayList is in the System.Collections namespace.

Public Properties

CapacityGets or sets the number of elements that the ArrayList can contain.

Count Gets the number of elements actually contained in the ArrayList.

IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly Gets a value indicating whether the ArrayList is read-only.

IsSynchronized Gets a value indicating whether access to the ArrayList is synchronized (thread-safe).

Public MethodsAdapter

Creates an ArrayList wrapper for a specific IList.

Add Adds an object to the end of the ArrayList.

AddRange Adds the elements of an ICollection to the end of the ArrayList.

BinarySearch Overloaded. Uses a binary search algorithm to locate a specific element in the sorted ArrayList or a portion of it.

Clear Removes all elements from the ArrayList.

Clone Creates a shallow copy of the ArrayList.

Contains Determines whether an element is in the ArrayList.

Navgujarat BCA Page 50 of 98

Page 51: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

CopyTo Overloaded. Copies the ArrayList or a portion of it to a one-dimensional array.

Equals Overloaded. Determines whether two Object instances are equal.

Insert Inserts an element into the ArrayList at the specified index.

InsertRange Inserts the elements of a collection into the ArrayList at the specified index.

Remove Removes the first occurrence of a specific object from the ArrayList.Repeat

Returns an ArrayList whose elements are copies of the specified value.

Reverse Overloaded. Reverses the order of the elements in the ArrayList or a portion of it.

Hashtable Class

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.

A hash function is an algorithm that returns a numeric hash code based on a key. The key is the value of some property of the object being stored. A hash function must always return the same hash code for the same key. It is possible for a hash function to generate the same hash code for two different keys, but a hash function that generates a unique hash code for each unique key results in better performance when retrieving elements from the hash table.

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.

Public Properties

Count

Gets the number of key-and-value pairs contained in the Hashtable.

IsFixedSize Gets a value indicating whether the Hashtable has a fixed size.

IsReadOnly Gets a value indicating whether the Hashtable is read-only.

Navgujarat BCA Page 51 of 98

Page 52: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

IsSynchronized Gets a value indicating whether access to the Hashtable is synchronized (thread-safe).

Item Gets or sets the value associated with the specified key.

Keys Gets an ICollection containing the keys in the Hashtable.

SyncRoot Gets an object that can be used to synchronize access to the Hashtable.

Values Gets an ICollection containing the values in the Hashtable.

Public Methods

Add

Adds an element with the specified key and value into the Hashtable.

Clear Removes all elements from the Hashtable.

Clone Creates a shallow copy of the Hashtable.

Contains Determines whether the Hashtable contains a specific key.

Remove Removes the element with the specified key from the Hashtable.

ToString Returns a String that represents the current Object.

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.

Navgujarat BCA Page 52 of 98

Page 53: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

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.

Public Properties

CapacityGets or sets the capacity of the SortedList.

CountGets the number of elements contained in the SortedList.

IsFixedSize Gets a value indicating whether the SortedList has a fixed size.

IsReadOnly Gets a value indicating whether the SortedList is read-only.

IsSynchronized Gets a value indicating whether access to the SortedList is synchronized (thread-safe).

Item Gets and sets the value associated with a specific key in the SortedList.

Keys Gets the keys in the SortedList.

SyncRoot Gets an object that can be used to synchronize access to the SortedList.

ValuesGets the values in the SortedList.

Public Methods

AddAdds an element with the specified key and value to the SortedList.

ClearRemoves all elements from the SortedList.

CloneCreates a shallow copy of the SortedList.

ContainsDetermines whether the SortedList contains a specific key.

SerializationBinder Class

Allows users to control class loading and mandate what class to load.

Navgujarat BCA Page 53 of 98

Page 54: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Public Methods

BindToTypeWhen overridden in a derived class, controls the binding of a serialized object to a type.

Equals (inherited from Object)Overloaded. Determines whether two Object instances are equal.

GetHashCode (inherited from Object)Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.

GetType (inherited from Object)Gets the Type of the current instance.

ToString (inherited from Object)Returns a String that represents the current Object.

serialization and deserialization

The last step is the serialization and deserialization of the items on the ListBox control. Serializationis the process of storing the object to a disk file, and deserialization is the opposite process.To serialize objects, we first store them into an ArrayList object. The ArrayList object is a dynamicarray that stores objects; it can be serialized as a whole. Likewise, the disk file is deserialized as anArrayList; then each element of the ArrayList is moved to the Items collection of the ListBox control.The ArrayList object is discussed in detail in Chapter 11, along with the techniques for serializingand deserializing its elements.

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.

Public Fields

MaxValue

Represents the largest possible value of a Char. This field is constant.

MinValue

Represents the smallest possible value of a Char. This field is constant.

Navgujarat BCA Page 54 of 98

Page 55: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Public Methods

CompareTo

Compares this instance to a specified object and returns an indication of their relative values.

Equals

Overridden. Returns a value indicating whether this instance is equal to a specified object.

IsDigit

Overloaded. Indicates whether a Unicode character is categorized as a decimal digit.

IsLetter Overloaded. Indicates whether a Unicode character is categorized as an alphabetic letter.

String Class

Represents text; that is, a series of Unicode characters.

Public Properties

Chars Gets the character at a specified character position in this instance.

Length

Gets the number of characters in this instance.

Public Methods

Clone

Returns a reference to this instance of String.

Compare

Overloaded. Compares two specified String objects.

CompareOrdinal

Overloaded. Compares two String objects by evaluating the numeric values of the corresponding Char objects in each string.

Navgujarat BCA Page 55 of 98

Page 56: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

CompareTo

Overloaded. Compares this instance with a specified object.

Concat

Overloaded. Concatenates one or more instances of String, or the String representations of the values of one or more instances of Object.

Copy Creates a new instance of String with the same value as a specified String.

CopyTo Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.

EndsWith Determines whether the end of this instance matches the specified String.

Equals Overloaded. Overridden. Determines whether two String objects have the same value.

Format

Overloaded. Replaces each format item in a specified String with the text equivalent of a corresponding object's value.

GetEnumerator

Retrieves an object that can iterate through the individual characters in this instance.

IndexOf Overloaded. Reports the index of the first occurrence of a String, or one or more characters, within this instance.

IndexOfAny

Overloaded. Reports the index of the first occurrence in this instance of any character in a specified array of Unicode characters.

Insert Inserts a specified instance of String at a specified index position in this instance.

Intern Retrieves the system's reference to the specified String.

IsInterned

Retrieves a reference to a specified String.

Navgujarat BCA Page 56 of 98

Page 57: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Join Overloaded. Concatenates a specified separator String between each element of a specified String array, yielding a single concatenated string.

LastIndexOf

Overloaded. Reports the index position of the last occurrence of a specified Unicode character or String within this instance.

LastIndexOfAny

Overloaded. Reports the index position of the last occurrence in this instance of one or more characters specified in a Unicode array.

PadLeft

Overloaded. Right-aligns the characters in this instance, padding on the left with spaces or a specified Unicode character for a specified total length.

PadRight

Overloaded. Left-aligns the characters in this string, padding on the right with spaces or a specified Unicode character, for a specified total length.

Remove

Deletes a specified number of characters from this instance beginning at a specified position.

Replace Overloaded. Replaces all occurrences of a specified Unicode character or String in this instance, with another specified Unicode character or String.

Split

Overloaded. Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a String array.

StartsWith

Determines whether the beginning of this instance matches the specified String.

Substring

Overloaded. Retrieves a substring from this instance.

ToCharArray

Overloaded. Copies the characters in this instance to a Unicode character array.

ToLower

Overloaded. Returns a copy of this String in lowercase.

ToString

Overloaded. Overridden. Converts the value of this instance to a String.

Navgujarat BCA Page 57 of 98

Page 58: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

ToUpper

Overloaded. Returns a copy of this String in uppercase.

Trim

Overloaded. Removes all occurrences of a set of specified characters from the beginning and end of this instance.

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.

Public Properties

Capacity

Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance.

Chars Gets or sets the character at the specified character position in this instance.

Length

Gets or sets the length of this instance.

MaxCapacityGets the maximum capacity of this instance.

Public Methods

Append

Overloaded. Appends the string representation of a specified object to the end of this instance.

Insert

Overloaded. Inserts the string representation of a specified object into this instance at a specified character position.

Remove

Removes the specified range of characters from this instance.

Replace

Overloaded. Replaces all occurrences of a specified character or string in this instance with another specified character or string.

Navgujarat BCA Page 58 of 98

Page 59: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

ToString

Overloaded. Overridden. Converts a StringBuilder to a String.

DateTime Structure

Represents an instant in time, typically expressed as a date and time of day.

Public Properties

Date

Gets the date component of this instance.

DayOfWeek

Gets the day of the week represented by this instance.

DayOfYear

Gets the day of the year represented by this instance.

Hour

Gets the hour component of the date represented by this instance.

Millisecond

Gets the milliseconds component of the date represented by this instance.

Minute

Gets the minute component of the date represented by this instance.

Month

Gets the month component of the date represented by this instance.

Now

Gets a DateTime that is the current local date and time on this computer.

Second

Gets the seconds component of the date represented by this instance.

Ticks

Gets the number of ticks that represent the date and time of this instance.

TimeOfDay

Gets the time of day for this instance.

Navgujarat BCA Page 59 of 98

Page 60: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Today

Gets the current date.

UtcNow

Gets a DateTime that is the current local date and time on this computer expressed as the coordinated universal time (UTC).

Year

Gets the year component of the date represented by this instance.

Public Methods

Add

Adds the value of the specified TimeSpan to the value of this instance.

AddDays

Adds the specified number of days to the value of this instance.

AddHours

Adds the specified number of hours to the value of this instance.

AddMilliseconds

Adds the specified number of milliseconds to the value of this instance.

AddMinutes

Adds the specified number of minutes to the value of this instance.

AddMonths

Adds the specified number of months to the value of this instance.

AddSeconds

Adds the specified number of seconds to the value of this instance.

AddTicks

Adds the specified number of ticks to the value of this instance.

AddYears

Adds the specified number of years to the value of this instance.

Compare

Compares two instances of DateTime and returns an indication of their relative values.

CompareTo

Compares this instance to a specified object and returns an indication of their relative values.

Navgujarat BCA Page 60 of 98

Page 61: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

DaysInMonth

Returns the number of days in the specified month of the specified year.

Equals

Overloaded. Overridden. Returns a value indicating whether an instance of DateTime is equal to a specified object.

IsLeapYear

Returns an indication whether the specified year is a leap year.

Subtract

Overloaded. Subtracts the specified time or duration from this instance.

ToFileTime

Converts the value of this instance to the format of a local operating system file time.

ToString

Overloaded. Overridden. Converts the value of this instance to its equivalent string representation.

TimeSpan Structure

Represents a time interval.

Public Properties

Days

Gets the number of whole days represented by this instance.

Hours Gets the number of whole hours represented by this instance.

Milliseconds Gets the number of whole milliseconds represented by this instance.

Minutes Gets the number of whole minutes represented by this instance.

Seconds Gets the number of whole seconds represented by this instance.

Navgujarat BCA Page 61 of 98

Page 62: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Public Methods

Add

Adds the specified TimeSpan to this instance.

Compare Framework.

Compares two TimeSpan values and returns an integer that indicates their relationship.

Duration Returns a TimeSpan whose value is the absolute value of this instance.

Equals Overloaded. Overridden. Returns a value indicating whether two instances of TimeSpan are equal.

FromDays Returns a TimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond.

Directory Class

Exposes static methods for creating, moving, and enumerating through directories and subdirectories.

Public Methods

CreateDirectory

Creates all directories and subdirectories as specified by path.

Delete Overloaded. Deletes a directory and its contents.

Exists Determines whether the given path refers to an existing directory on disk.

GetCreationTime Gets the creation date and time of a directory.

GetCreationTimeUtc Gets the creation date and time, in coordinated universal time (UTC) format, of a directory.

GetCurrentDirectory Gets the current working directory of the application.

Navgujarat BCA Page 62 of 98

Page 63: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

GetDirectories Overloaded. Gets the names of subdirectories in the specified directory.

GetDirectoryRoot

Returns the volume information, root information, or both for the specified path.

GetFiles

Overloaded. Returns the names of files in the specified directory.

File Class

Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

Public Methods

AppendText

Creates a StreamWriter that appends UTF-8 encoded text to an existing file.

Copy

Overloaded. Copies an existing file to a new file.

Create

Overloaded. Creates a file in the specified path.

CreateText

Creates or opens a file for writing UTF-8 encoded text.

Delete

Deletes the specified file. An exception is not thrown if the specified file does not exist.

Exists

Determines whether the specified file exists.

Open

Overloaded. Opens a FileStream on the specified path.

OpenRead

Opens an existing file for reading.

OpenText

Opens an existing UTF-8 encoded text file for reading.

Navgujarat BCA Page 63 of 98

Page 64: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

OpenWrite

Opens an existing file for writing.

DirectoryInfo Class

Exposes instance methods for creating, moving, and enumerating through directories and subdirectories.

Public Properties

Attributes

Gets or sets the FileAttributes of the current FileSystemInfo.

Gets or sets the creation time of the current FileSystemInfo object.

CreationTimeUtc Gets or sets the creation time, in coordinated universal time (UTC), of the current FileSystemInfo object.

Exists

Overridden. Gets a value indicating whether the directory exists.

Extension

Gets the string representing the extension part of the file.

FullName

Gets the full path of the directory or file.

Public Methods

Create

Creates a directory.

CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

CreateSubdirectory

Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.

Navgujarat BCA Page 64 of 98

Page 65: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Delete

Overloaded. Overridden. Deletes a DirectoryInfo and its contents from a path.

Overloaded. Determines whether two Object instances are equal.

GetDirectories

Overloaded. Returns the subdirectories of the current directory.

GetFiles

Overloaded. Returns a file list from the current directory.

FileInfo Class

Provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

Public Properties

Attributes

Gets or sets the FileAttributes of the current FileSystemInfo.

CreationTime

Gets or sets the creation time of the current FileSystemInfo object.

CreationTimeUtc Gets or sets the creation time, in coordinated universal time (UTC), of the current FileSystemInfo object.

Directory

Gets an instance of the parent directory.

DirectoryName

Gets a string representing the directory's full path.

Public Methods

AppendText

Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.

CopyTo

Overloaded. Copies an existing file to a new file.

Navgujarat BCA Page 65 of 98

Page 66: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Create

Creates a file.

CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

CreateText

Creates a StreamWriter that writes a new text file.

Delete

Overridden. Permanently deletes a file.

Equals

Overloaded. Determines whether two Object instances are equal.

GetHashCode

Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.

Open

Overloaded. Opens a file with various read/write and sharing privileges.

OpenRead

Creates a read-only FileStream.

Path Class

Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.

Public Fields

PathSeparator

A platform-specific separator character used to separate path strings in environment variables.

Public Methods

ChangeExtension

Changes the extension of a path string.

Navgujarat BCA Page 66 of 98

Page 67: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Combine

Combines two path strings.

GetDirectoryName

Returns the directory information for the specified path string.

GetExtension

Returns the extension of the specified path string.

GetFileName

Returns the file name and extension of the specified path string.

StreamWriter Class

Implements a TextWriter for writing characters to a stream in a particular encoding.

For a list of all members of this type

Methods:

Close

Overridden. Closes the current StreamWriter and the underlying stream.

Equals Overloaded. Determines whether two Object instances are equal.

Flush Overridden. Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

GetHashCode Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.

Write Overloaded. Overridden. Writes to the stream.

StreamReader Class

Implements a TextReader that reads characters from a byte stream in a particular encoding.

Navgujarat BCA Page 67 of 98

Page 68: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Close

Overridden. Closes the StreamReader and the underlying stream and releases any system resources associated with the reader.

Equals

Overloaded. Determines whether two Object instances are equal.

InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance.

Peek

Overridden. Returns the next available character but does not consume it.

Read

Overloaded. Overridden. Reads the next character or next set of characters from the input stream.

ReadBlock

Reads a maximum of count characters from the current stream and writes the data to buffer, beginning at index.

ReadLine

Overridden. Reads a line of characters from the current stream and returns the data as a string.

ReadToEnd

Overridden. Reads the stream from the current

BinaryReader Class

Reads primitive data types as binary values in a specific encoding.

Public Methods

Close

Closes the current reader and the underlying stream.

Equals

Overloaded. Determines whether two Object instances are equal.

GetHashCode

Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.

PeekChar

Returns the next available character and does not advance the byte or character position.

Navgujarat BCA Page 68 of 98

Page 69: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Read

Overloaded. Reads characters from the underlying stream and advances the current

BinaryWriter Class

Writes primitive types in binary to a stream and supports writing strings in a specific encoding.

Public Methods

Close

Closes the current reader and the underlying stream.

Equals

Overloaded. Determines whether two Object instances are equal.

ReadBytes

Reads count bytes from the current stream into a byte array and advances the current position by count bytes.

ReadChar

Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.

Navgujarat BCA Page 69 of 98

Page 70: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

QUESTION-ANSWER

1 What are objects and properties? How are they related to each other?

Ans: - An object is a combination of code and data that can be treated as a unit. An object can be a piece of an application, like a control or a form. An entire application can also be an object.

Objects let you declare variables and procedures once and then reuse them whenever needed. For example, if you want to add a spell checker to an application you could define all the variables and support functions to provide spelling check functionality to your application. However, if you create your spell checker as a class, you can reuse it in other applications by adding a reference to the compiled assembly. Better yet, you may be able to save yourself some work by using a spell checker class that someone else has already developed.

Properties represent information stored in an object. The values properties are retrieved and set with assignment statements the same way that variables are retrieved and set. Objects are created as identical copies of their class. Once they exist as individual objects, however, their properties can be changed. For example, if you add three check boxes to a form, each check box button object is an instance of the CheckBox class. The individual CheckBox objects share a common set of characteristics and capabilities (properties, fields, methods, and events), defined by the class. However, each has its own name, can be separately enabled and disabled, can be placed in a different location on the form

The following example sets and retrieves the value of a property.

Dim X As Integer = 8Dim Obj1 As New Class1 ' Declares an instance of a class.Obj1.Prop1 = X ' Property assignment. Assigns the number 8 to Prop1.X = Obj1.Prop1 + 1 ' Retrieval. The variable X contains the number 9.

2 Explain the difference between ByRef and ByVal . When would each be used?

Ans: - The ByRef keyword indicates that an argument is passed in such a way that the called procedure can change the value of a variable underlying the argument in the

Navgujarat BCA Page 70 of 98

Page 71: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

calling code. While , The ByVal keyword indicates that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code.

The ByRef keyword is used in,

Declare Statement, Function Statement, Sub Statement

The ByVal keyword is used in,

Declare Statement, Function Statement , Property Statement, Sub Statement

3 What is the purpose of a class?

Ans: - The classes that you have worked with up until now have generated visual objects sucha as a text boxes and labels.These were easily created from the toolbox at design time.You can also create objects at runtime.One Example a class that you would instantiate at runtime is the font class .

O-4 What are property procedures and what is their purpose?

Ans: - A Property procedure is a series of Visual Basic statements that manipulate a custom property on a module, class, or structure. Property procedures are also known as property accessors.

A property differs from a public variable or a field in the following respects:

You implement a property with executable code (its Property procedures), rather than with a single declaration statement. Property procedures are executed when the property value is set or retrieved. This allows a class to perform custom actions when client code accesses the property. A property does not have any storage location associated with its declaration. Although its Property procedures often define local variables and constants, these are usually not available to the code accessing the property. Therefore, while you can include a variable or a field as a member of a structure or array, you cannot do this with a property. You can define a property as read-only, write-only, or read/write. The default is read/write. Visual Basic provides the following Property procedures: Get procedures return the value of a property; they are called when the property is accessed in an expression. Set procedures set a property to a value, including an object reference; they are called when a value is assigned to the property.

You usually define Property procedures in pairs, using the Get and Set keywords, but you can define either procedure alone if the property is read-only (Get) or write-only (Set).

Navgujarat BCA Page 71 of 98

Page 72: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Property Declaration

A property itself is defined by a block of code enclosed within the Property and End Property statements. Inside this block, each Property procedure appears as an internal block enclosed within a declaration statement (Get or Set) and an End statement. The syntax for declaring a property and its procedures is as follows:

[Default] [accessibility] Property propertyname[(argumentlist)] As datatypeGet ' ... Return expression ' expression is returned as property's value.End GetSet [(ByVal newvalue As datatype)] ' ... lvalue = newvalue ' newvalue is the new value to be assigned.End SetEnd Property

The accessibility can be Public, Protected, Friend, Protected Friend, or Private.

You can define properties in classes, structures, and modules. Properties are Public by default, which means you can call them from anywhere in your application.

5 What steps are needed to assign property values to an object?

Ans: - TO assign property at design time we can set through property window or we can assign by mentioning its property in code window.

6 How can you write methods for a new class?

Ans: -You can create a method by adding sub procedures and functions for the behaviours needed by the class. For this class,you will add a method as a function procedure to calculate the extended price,which is the price for the book multiplied by the quantity.

Step 1 :After the property procedure,type in public function extended price as decimal and press Enter.Notice that the editor adds the parenthesis after the function name

Step 2 : Type the code for the function

Public function extendedprice()as decimal

Calculate the extended price

Return Mintquantity*mdecprice

End function

Navgujarat BCA Page 72 of 98

Page 73: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

8 What is parameterized constructor?

Ans: - Initializes a new instance of the ParameterModifier class with the number of parameters to modify.

Public Sub New( _ ByVal parameterCount As Integer _)

Parameters

parameterCount The number of parameters to modify

9 Explain the differences between a pretest and posttest in a Do/Loop?

Ans: - The first form of the loop test for the compilation at the top of the loop called pretest. While The second form of the loop test for the compilation at the bottom of the loop

11 In What procedure do you write the logic for sending output to the printer?

Ans: -

12 Define the following terms:

(a) Array (b) Element (c)Subscript (d) Index (e) Subscripted variable

Ans: -

(a) Arraay : - Collection of similar data type

element- value of specified index in an array

15 Discuss how and when the value of the loop index changed throughout the processing of loop?

Ans: - Loop terminate based on a condition that you specify. Execution of loop continues while a condition is true until condition is true. You can choose the place and

Navgujarat BCA Page 73 of 98

Page 74: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

condition at the top or bottom of the loop. When the check condition second time that time increment or decrement loop index.

18 Define the following terms:

(a) Array: An Array is a list or series of value, similar to a list box or combo box. You can think of an array as a list box without the box-without the visual representation. Any time you need to keep a series of variables for later processing, such as re-ordering, calculating or printing. You need to set up an array.(b) Element: Each field of data in a variable declares as a structure is referred as an element of the structure. To access element, use the dot notation similar to that used for object, specify variable. Element.(c) Subscript: The real advantage of using an array is not realized until you use variable for subscript in place of the constant. Subscript may be constants, variable or numeric expression. Although the subscript may be integers.(d) Index: The subscript (which may also be called an index) inside the parenthesis is the position of the element within the array.(e) Subscripted Variable: An array is a series of the individual variable, all reference by the same name. Sometimes array are referred to as a table or subscripted variable. For an array for sorting names, you may have strName(0), strName(1) strName(2) and so on.

20 Describe the logic of a table lookup?

Ans: The technique used to find the subscript is called a table look-up. Things don’t always workout as neatly as having sequential group number that can be used to access the table directly, sometimes you will have to do a little work to find the correct value. Reconsider the eight scout troops and their ticket sales. Now the groups are not numbered 1 to 8 but 101,103,110,115,121,123,130 and 145.The group number and the number of tickets sold is still input, and the number of tickets must be added to the correct total. But now you must do one more step-determine to which array element to add the ticket sale, using a table lookup.

The first step in the project is to establish a structure with the group number and the total and then dimensions an array of the structure. Before any processing is done, you must load the group number into the table. The best place to do is in the Form_LoadEvent procedure, which is executed once as the form is loaded into the memory. During program execution the user still enters the group number and the number of tickets sold into text box.

21 Name some situations in which it is important to perform validation when working with subscripted variables.

Ans: A subscript must reference a valid element of the array. If a list contains 10 names, it would not make sense to ask: What is the 15th name on the list? Or what is the 2 ½ th name

Navgujarat BCA Page 74 of 98

Page 75: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

on the list? Visual Basic rounds fractional subscripts and throws an exception for a subscript that is out of range.Dim strName(20) As StringConst intValue As Integer=10After execution of the preceding statements, which of the following are valid subscripts?

1. strName(20)2. strName(intValue)3. strName(intValue*2)4. strName(intValue*3)5. strName(0)6. strName(intValue-20)7. strName(intValue/3)8. strName(intValue/5-2)

22 Compare a two-dimensional table to an array of a structure.

Ans: To define a two-dimensional array or table the Dim statement specifies the number of rows and columns in the array. The row is horizontal and the column is vertical. Both of these two statements establish an array of elements. Just as with the single dimensional array you can’t specify the number of element with the parenthesis and specify initial value. How can you initialize values in a two-dimensional table?Ans: Numeric array elements are initially set to 0 and string element are set to empty string and of course you can assign initial value when you declare the array. But many situations require that you reinitialize array to 0 or some other value.Dim intRow As IntegerDim intColumn As IntegerFor intRow=0 To 2 For intColumn=0 To 3

23 what is an object ? a property? A method?

Ans: - In OLE, a programming structure encapsulating both data and functionality that are defined and allocated as a single unit and for which the only public access is through the programming structure's interfaces. A COM object must support, at a minimum, the IUnknown interface, which maintains the object's existence while it is being used and provides access to the object's other interfaces. See also COM and Interface. A property: Information that is associated with an object. In OLE, properties fall into two categories: run-time properties and persistent properties. Run-time properties are typically associated with control objects or their containers. For example, background color is a run-time property set by a control's container. Persistent properties are associated with stored objects. See also Persistent properties and Run-time properties.

A method:- There are two types of methods: subroutines, which do not return values, and functions, which do. The body and End construct of a method may only be omitted if the

Navgujarat BCA Page 75 of 98

Page 76: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

method is defined in an interface or has the MustOverride modifier. If no return type is specified on a function and strict semantics are being used, a compile-time error occurs; otherwise the type is implicitly Object. The accessibility domain of the return type and parameter types of a method must be the same as or a superset of the accessibility domain of the method itself.

MethodDeclaration ::= SubDeclaration | FunctionDeclaration

SubDeclaration ::=   [ Attributes ] [ ProcedureModifier+ ] Sub Identifier [ ( [ FormalParameterList ] ) ][ HandlesOrImplements ] LineTerminator   [ Block ]   [ End Sub LineTerminator ]

FunctionDeclaration ::=   [ Attributes ] [ ProcedureModifier+ ] Function Identifier[ ( [ FormalParameterList ] ) ] [ As [ Attributes ] TypeName ][ HandlesOrImplements ] LineTerminator   [ Block ]   [ End Function LineTerminator ]

ProcedureModifier ::=   AccessModifier |   Shadows |   Shared |   Overridable |   NotOverridable |   MustOverride |   Overrides |   Overloads

HandlesOrImplements ::= HandlesClause | MethodImplementsClause

25 Explain the how to create a new object?3

Ans:- An object-creation expression is used to create a new instance of a class type or a structure type. The type of an object creation expression must be a class type or a structure type and cannot be a MustInherit class. Given an object creation expression of the form New T(A), where T is a class type or structure type and A is an optional argument list, overload resolution determines the correct constructor of T to call. If no constructor is callable, a compile-time error occurs; otherwise the expression results in the creation of a new instance of T using the chosen constructor. If there are no arguments, the parentheses may be omitted.

ObjectCreationExpression ::= New TypeName [ ( [ ArgumentList ] ) ]

Navgujarat BCA Page 76 of 98

Page 77: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

26 What actions trigger the constructor and destructor method of a object?

Ans:- Constructors are special methods that allow control over initialization. They are run after the program begins or when an instance of a type is created. Unlike other members, constructors are not inherited and do not introduce a name into a type's declaration space. Constructors may only be invoked by object-creation expressions or by the .NET Framework; they may never be directly invoked.

It is useful to think of variable initializers as statements that are automatically inserted in the block of a constructor. The following example contains several variable initializers

The example corresponds to the code shown below, where each comment indicates an automatically inserted statement:

Imports System.CollectionsClass A Private x, y, count As Integer Public Sub New() MyBase.New() ' Invoke object() constructor. x = 1 ' This is a variable initializer. y = - 1 ' This is a variable initializer. count = 0 End Sub Public Sub New(n As Integer) MyBase.New() ' Invoke Object constructor. x = 1 ' This is a variable initializer. y = - 1 ' This is a variable initializer. count = n End SubEnd Class

Class B Inherits A Private sqrt2 As Double Private items As ArrayList Private max As Integer Public Sub New() Me.New(100) items.Add("default") End Sub Public Sub New(n As Integer) MyBase.New(n - 1)

Navgujarat BCA Page 77 of 98

Page 78: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

sqrt2 = System.Math.Sqrt(2.0) ' This is a variable initializer. items = New ArrayList(100) ' This is a variable initializer. max = n End SubEnd Class

Destructor:- "Destructor" functions are the inverse of constructor functions. They are called when objects are destroyed (deallocated). Designate a function as a class's destructor by preceding the class name with a tilde (~). For example, the destructor for class String is declared: ~String().

The destructor is commonly used to "clean up" when an object is no longer necessary. Consider the following declaration of a String class:

// spec1_destructors.cpp#include <string.h>

class String{public: String( char *ch ); // Declare constructor ~String(); // and destructor.private: char *_text;};

// Define the constructor.String::String( char *ch ){ // Dynamically allocate the correct amount of memory. _text = new char[strlen( ch ) + 1];

// If the allocation succeeds, copy the initialization string. if( _text ) strcpy( _text, ch );}

// Define the destructor.String::~String(){ // Deallocate the memory that was previously reserved // for this string. delete[] _text;}void main(){

Navgujarat BCA Page 78 of 98

Page 79: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

}28 Differentiate between overloading and overriding?

Ans:- Overloading:-

Overloading is the only way to declare identically named entities of the same kind in a declaration space. Only methods, instance constructors, and properties may be overloaded.

Overloaded type members must possess unique signatures. The signature of a type member consists of the name of the type member and the number and types of the member's formal parameters.

The following are not part of a member's signature, and hence can not be overloaded on:

Modifiers to a type member (for example, Shared or Private). Modifiers to a parameter (for example, ByVal or ByRef). The names of the parameters. The return type of a method. The element type of a property.

Ovrriding:-

The Overrides modifier indicates that a method overrides a base-type overridable method with the same signature.

Certain combinations of these modifiers are not valid:

Overridable and NotOverridable are mutually exclusive and cannot be combined. MustOverride implies Overridable (and so can't specify it) and cannot be combined with NotOverridable. MustOverride methods cannot override other methods, and so cannot be combined with the Overrides modifier. NotOverridable cannot be combined with Overridable or MustOverride. Overrides implies Overridable (and so can't specify it) and cannot be combined with MustOverride.

There are also additional restrictions on overridable methods:

A MustOverride method may not include a method body or an End construct, may not override another method, and may only appear in MustInherit classes. If a method specifies Overrides and there is no matching base method to override, a compile-time error occurs. An overriding method may not specify Shadows. A method may not override another method if the overriding method's accessibility domain is not equal to or greater than the accessibility domain of the method being overridden.

Navgujarat BCA Page 79 of 98

Page 80: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Private methods may not be Overridable, NotOverridable, or MustOverride, nor may they override other methods. Methods in NotInheritable classes may not be declared Overridable or MustOverride.

29 IN What situation would a loop be used in a producer?

Ans:- A control structure allows you to control the flow of your program execution Using control structure you can test the condition depanding on the result and execute one or more line of code repetitively

30 Explain different between do / while and For loop?

Ans:- DO/ WHILE:-If condition is True, all statements in statements are executed until the Wend statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is repeated. If it is not True, execution resumes with the statement following the Wend statement.

While...Wend loops can be nested to any level. Each Wend matches the most recent While.

Note   The Do...Loop statement provides a more structured and flexible way to perform looping.

The following example illustrates use of the While...Wend statement:

Dim CounterCounter = 0 ' Initialize variable.While Counter < 20 ' Test value of Counter. Counter = Counter + 1 ' Increment Counter. Alert CounterWend ' End While loop when Counter > 19.FOR LOOP:- Changing the value of counter while inside a loop can make it more difficult to read and debug your code.

Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:

For I = 1 To 10 For J = 1 To 10 For K = 1 To 10

Navgujarat BCA Page 80 of 98

Page 81: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

. . . Next NextNext

31.What is the Purpose of the Name Property Control ? Ans:=>

If you Change the name of the form you Must set project’s startup object property to the new name of the form. The name property gives the menu item a name similar to naming other control. With the use of name property we can change the label name, List box name, Button Name, Controls Names.

33.What is the purpose of the Text property of a button ? the Text Property of a form ? Ans:=>

We can set the text in a button with a text Property in the tool bar button collection editor.

The text property of the control Determines what will be displayed on the form, with text property we can change text of the form.

34.What Property must be set to center text in a label ? What should be the value of the property? Ans:=>

The Text Align ( Alignment) Property allow you to set the alignment of the text within the label

Text Align ( MiddleCenterThis Property will be set When you Want to Set The center Text in a label

35.How does the behavior of radio buttons differ from the behavior of check boxes ? Ans:=>

Check Boxes :- They are Square.

Radio Button :-They are Round.

Check Boxes :-Check Boxes can work independently.

Radio Button :- Radio Buttons are intended to work in groups.

Check Boxes :- It allow Multiple selection.

Radio Button :- When you select one Radio Button in Group the others are

automatically deselected. Check Boxes :-

Navgujarat BCA Page 81 of 98

Page 82: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

It allow The user to select and deselect an option. Radio Button :-

It use when only one button of group may be selected.

36.Explain how to make a graphic appear in a picture box control. Ans:=> To Display a Graphic from a bitmap, icon, JPEG, GIF or other image file tape you can see a picture box - from the picture boxes. you can set the IMAGE property to the image you want to display, either at disgn time or at run time. You can clip and position an image with the "size mode" poperty

Picturesizemode :- @ Normal :-

Standard picturebox behaviour. @ Autosize:-

Fits the picture box to the image. @ Stretchinage:-

Allow you to stretch the image in code.@ Center Image:-

Centers the image in the picture box.

37.What is the purpose of Keyboard access keys ? How can you define them in your project ? How do you they operate at run time ?

Ans:=> Access key allow user to open a menu by pressing the Alt(Alter) key and a letter key.

To open the edit menu in all windows application for, eg. You can press Alt+E.

E is the edit menu's access key.

38.Explain the purpose of the AcceptButton and CancelButton properties of the form. Give an example of a good use for each ?

Ans:=> Acceptbutton :

You Can make one of your button the default button by setting the acceptbutton property of the form to the button name.when the user presses

enter that button is automatically selected.Cancelbutton:

The Cancelbutton is the button that is selected when the user pressesthe Esc key. you can make a button the cacelbutton by setting the form's cancelbutton property.an example of good time to set the cancel button

property is on a form with ok & cancel button.

39.What is Tooltip ? How can you Make a Tooltip appear? Ans:=>

Tooltip are those small windows that appear with explanatory text when

Navgujarat BCA Page 82 of 98

Page 83: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

you letthe mouse rest on a control or window . That's what Tool tips are used for -to give quickhelp when the mouse rest on an item.

To connect a tooltip with a control you use it's set tool tip method.Syntex:-

Tooltip.set Tooltip ( button1."this is a button") 40.what is Focuse? How can you Control Which object has the Focuse ? Ans:=>

This method moves the Focus to the control to which the method applies, regardless of the conrol that has the Focus at the time. Your validation routin could move the Focus to the control with an erroneous entry with the following statement:

Textbox1.FocusIt's also possible to "trep" the focus to a specific Text Box control until the user

enters a valid value,by calling the Focus mathod from within the Leave event.The following code sagment doesn't allow users to move the Focus to another control while TextBox1 doesn't contain a valid numeric value:

Private sub Textbox1_leave(Byval sender As Object ,-Byval e as System.EventArgs) Handles Textbox1.Leave

If Not IsNumeric(Textbox1.Text)Then Textbox.Focus()End Sub

41. What is messagebox and When should use one? Ans:=> With the use of messagebox you can use the msgbox and input box functions.you can also use the messagebox class built into the .net framework to display messagesand accept input from the user.

Syntex:-Messagebox.show ( arguments )several choices for argument list introduce concept of overloded functionsmultiple signature to choose formmessagebox.show(textmessage)messagebox,show(textmessage,titalbar Text)

43.Explain the difference between a menu & a submenu. Ans:=>

Main menu is the context menu. Inside of main menu is called sub menu.44.How Can the user know if a menu item contains a submenu? Ans:=>

When our mouse cursor is goes on to the main menu then inside menu will be open thus we know that Main menu item contains.45.Name at least three types of common dialogboxes.

Navgujarat BCA Page 83 of 98

Page 84: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Ans:=> Openfile DialogboxSavefile DialogboxFontcolor DialogboxPrint DialogboxPrint Preview Dialogbox

46.What is context menu ? How would you attech a context menu to a contral? Ans:=>

Context menu are those handy menuse that pop up over controls, usually when you right - Click them.

Object MarshalbyRefObject Component Menu

ContextMenuThere are some public properties of contextmenuMethod MeansGetcontextMenu Gets the Context Menu that contains this menu

48.What is listbox? A combobox? Ans:=> Combo Box:=> The windows forms combobox control is use to display the data in a drop-down combobox.The combobox is made up of two parts-the top part is a textbox that allow the user to type in all or part of a list item.the another part is a list box that displays a list of item from which the user can select one or more. You can set and access the text in a combobox's text box with the text property .

To add or delete Items in a combo box control,use the Items.Add, Item.Insert,Item.Clear,Item.Addrange,Items.Remove or Item.Removeat method

List Box:->List box displays a list of items from which the user can select one or more . If

there are too many Items to display at once, a scroll bar automatically appers to let the users scroll through the list. you also can scroll List Boxes horizontally when you set the Multi Colmn property to True.

The SelectIndex property returns an integer value that corresponds to the selected items 49.Name and decribe the three styles of comboboxes? Ans:=>

There are Three types of Comboboxes 1. Simple Combo Box :-

Include a text box and a list which does not drop down. the user can select from the list or type in the text box. The size of the simple combo box include both the edit and list portion. By default a simple combo box is sized so that non of the list is displayed.

Navgujarat BCA Page 84 of 98

Page 85: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Increase the Hight property to display more of the list.2. Drop down Combo Box :-

Includes a drop down list and a text box. the user can select from the list or type in the text box.

3. Drop down list combo Boxes :-This style allows selection only from drop down list. this is the good one to keep

in mind when you want to restrict the user's input, But if you want to use this one, You also should consider simple list box.

51.Explain the purpose of the selectedindex property and the item.count property. Ans:=>

SelectedIndex:- You can use the selectedindex property to get the selectedlist item .you can

change selected item by changing the selectedindex value in code , which will make the corresponding item appear in the text portion of the combobox as with list boxes if no item is selected , the selected index value is -1. if the first item in the list is selected, then the selectedindex value is 0.

Item.count:- The item.count property reflects the number of item in the list ( The value of

the item.count property is always one more than the largest possible selectedindex value selectedindex is Zero - based).

52.When and how is information placed inside a listbox or combobox. Ans:=>

A combobox is a combination of a textbox and a list box , so at design time , you can change text in the text box part by changing the Text property . You change the items in the list box part with the item property (this item opens the string collection Editor discussed for listboxes when you click it in the property window) at design time.

As with list boxes , you also can use the items.insert ,items.add and items.addrange method to add items to the listpart of a combo box. 53.What is the purpose of the printdocument control? The print preiview dialog

control? Ans:=>

The way You print documents in vb has become fairly involved , revolving around the printdocument class.You add an object of this class to a project,and then handle event like printpage,which is called every time a new page is to be printed when it is added to a form , the printdocument component appears in the tray at the bottom of the windows form designer

Printpreview dialogs:-You use printpreview dialogs to let the user see what a document will look like

when it's printed. this dialog is supported with the printpreviewdialog class.this dialog contains buttons for printing, zooming in, displaying one or multiple pages , and closing the dialogbox.

Basics of vb.net

Navgujarat BCA Page 85 of 98

Page 86: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

53 What are the properties and events? Explain with example.=>Properties:- Properties are use to set configuration data for objects, such as text in a text box or the width of a list box .Properties provides interface to set or get the value of data internal to an object. Properties uses Get and Set the procedure in a property statement.Example:

In this eg. we are creating a read/write property named Prop1 in Module2, and storing the property's value in private text string named Property Value in Module2 .Module Module1Sub Main ()

....

....

....End Sub End ModuleModule Module2

Private Property Value as string Public Property Prop1 () As StringGetReturn Property ValueEnd GetSet (By Val Value As String)

Property Value =Value End SetEnd Property

End ModuleEvents:- An action that may be caused by the user, such as a click , drag, key press or scroll. Events can also be triggered by an internal action such as repainting the form or validating the user input. Example:-

54 What are the different editions of Microsoft VB.Net?=>The different editions of Microsoft VB.Net are:

1) Academic edition 2) Professional edition3) Enterprise Developer edition4) Enterprise Architect edition

56 What is IDE? Explain.=>A development environment such as visual studio, is called an IDE(Integrated Development Environment).The IDE consists of various tools including a form designer, which allows you to visually create a form; an editor for entering and modifying program code. In earlier versions of Visual Studio, each language had its own IDE. For example, to create a VB project you would use the VB IDE, and to create a C++ project you would use the C++ IDE. But in Visual Studio.Net, you use the one IDE to create projects in any of the .NET languages.

Navgujarat BCA Page 86 of 98

Page 87: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

The different types of IDE is as below:- -The start page -Tool box

-Menu bar -New project Dialogbox -Object Browser -Solution Explorer

-Class View Window -Component Tray -The server explorer -Property Window

57 What is the difference between Keyup and Keydown event?=>Keyup:-

It happens when key is released while the control has focus. Keydown:-

It happens when a key is pressed down while the control has focus.58 What is Message Box? How to write the multipleline messagebox?=>Message box is a function which is an easy way to add multiple forms already built in a Visual Basic.We can also use the MessageBox class built into the .Net Framework to display messages and accept input from the user.

Arguments passed to this function:1) Prompt2) Buttons

3) TitleThis function returns the value from the MsgBoxResult enumeration.

Eg:Private Sub Button1_Click(ByVal sender As System.Object,

(ByVal e As System.EventArgs) Handles Button1.ClDim Result As Integer Result=MsgBox("This is a Message Box!", MsgBoxStyle.OKCancel + _MsgBoxStyle.Information + MsgBoxStyle.SystemModal, "Message Box")If (Result= MsgBoxResult.OK) then

TextBox1.Text="You clicked OK"End If

End Sub59 What is the difference between VB and VB.Net?=>VB:- 1) Visual Basic 6.0 is revolutionary and far reaching. 2) A great number of techniques such as data handling, and many controls, project types and other aspects of visual basic 6.0 are no longer available at all. 3) It is less popular than VB.Net 4) It is not fully object-oriented language VB.Net:- 1)VB.Net has been more than four years in the making, and it represents entirely new directions for visual basic.

Navgujarat BCA Page 87 of 98

Page 88: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

2) A great number of techniques such as data handling, and many controls, project types and other aspects of VB.Net are easily available. 3) It is more popular than visual basic 6.0. 4) It is fully object-oriented language.60 What are the rules for naming the variables?=>61 What is the Implicit and Explicit Declarations?

=> Implicit Declarations:-

If you turn explicit declaration off, you can implicitly declare a variable by simply using t in your code. All implicitly declared variables are given the data type Object. However, your application is more efficient if you declare all your variables explicitly and with a specific data type. This reduces the incidence of naming-conflict errors and spelling mistakes. It also allows the compiler to detect potential run-time errors such as assigning an Integer to a Short.

You can write a function in which you do not declare a local variable, as in the following example:

Function SafeSqrt(Num) TempVal = Math.Abs(Num) ' Make sure value is positive for square root. Return Math.Sqrt(TempVal)End Function

Explicit Declarations:-

Explicit declarations has been in effect for the module containing the SafeSqrt function in the preceding example, Visual Basic would have recognized TempVal and TemVal as undeclared variables and generated errors for both of them. As a result, you would then explicitly declare TempVal, as follows:

Function SafeSqrt(Num As Single) As Single Dim TempVal As Single = Math.Abs(Num) Return Math.Sqrt(TemVal)End Function70 What is the difference between procedure and function? Explain with the example.=>Procedure:- A callable series of statements that may or may not return value.When the series of statements terminates ,control returns to the statements that call the procedure.Function:-A procedure that returns the value.11)What is Implicit and Explicit Conversions?

=> Conversions can be either implicit or explicit.

Navgujarat BCA Page 88 of 98

Page 89: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Implicit Conversions:-

Implicit conversions occur without any special syntax. The following is an example of implicit conversion of an Integer value to a Long value:

Module Test

Sub Main() Dim intValue As Integer = 123 Dim longValue As Long = intValue Console.WriteLine(intValue & " = " & longValue) End SubEnd Module

Explicit Conversions:-

Explicit conversions, on the other hand, require cast operators. Attempting to do an explicit conversion on a value without a cast operator causes a compile-time error. It is Set to On or Off. On is the default. Requires declaration of variables before they are used. (This is the default)

The following example uses an explicit conversion to convert a Long value to an Integer value.

Module Test

Sub Main() Dim longValue As Long = 134 Dim intValue As Integer = CInt(longValue) Console.WriteLine(longValue & " = " & intValue) End Sub

End Module

71 What are the three steps for planning and creating Visual Basic Projects? Describe what happens in each step.=>1) Setting Up the user interface 2) Defining the properties 3) Creating the code 72 What is the purpose of these visual basic file types: .sln , .suo , .vb?=>.sin= solution file. .suo=solution user option file. .vb=Any file from following.

-Basic window form -A data form -A user control

Navgujarat BCA Page 89 of 98

Page 90: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

-Module file -A code file

-custom control -Inherited form -Windows services -The Output Window -Form Designers -Graphical Designers

73 When is the visual basic in design time? run time? break time?=>Visual Basic has three distinct modes.Design Time:- While we are designing the user interface and writing code, we are in design time.Run Time:- When we are testing and running your project, we are in runtime.Break Time:- If we get a run-time error or pause project execution, we are in break time. 74 What is visual basic event? Give some examples of events.=> An action that may be caused by the user, such as a click , drag, key press or scroll. Events can also be triggered by an internal action such as repainting the form or validating the user input.76 What is a syntax error, when does it occur, what might cause it?=>When we break Vb’s rules for punctuation, format or spelling, we generate a syntax error.The syntax error that the editor cannot identify are found and reported by the compiler as it attempts to convert the code into intermediate machine language.77 What is a run-time error, when does it occur, what might cause it?=>If a project halts during execution, it is called runtime error or an exception. Statements that cannot execute correctly cause runtime error. Run time errors can be caused by attempting to do impossible arithmetic operations. 78 What is a logic error, when does it occur, what might cause it?=>The project runs but produces incorrect result is called logic error. When the results of the calculation are incorrect or the text appears, or the text is OK but appears in the wrong location, logic error will occur. 79 What does context-sensitive Help mean? How can you use it to see the Help page for a button?=>A quick way to view Help on any topic is used to context-sensitive Help. Select a VB object, such as a form or control, or place the insertion point in a word in the editor, and press F1.The corresponding help topic will appear in the document window, if possible, saving you a search. 80Name and give the purpose of five types of data available in Visual Basic.=>Data types:-single:-It can handle floating point values.Double:-It can also handle floating point values.Boolean:-

Navgujarat BCA Page 90 of 98

Page 91: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

It takes values like true or false only.String:-It takes the string.Int:-It takes the only integer values.81What does declaring a variable mean?=>We will use Dim statement to declare a variable. This statement is used at module, class, structure, procedure or block level.For example:Dim c as intIt means that we have taken c variable as integer.82 What effect does the location of a Dim statement have on the variable it declares?=>Although there are several ways to declare a variable, the most commonly used statement is the Dim statement.

The reserved word Dim is really short for dimension, which means size.When you declare a variable, the amount of memory reserved depends on it’s data type. 83Explain the difference between a constant and a variable.

=> Constant:-

1) You use the Const statement to declare a constant and set its value.

2) By declaring a constant, you assign a meaningful name to a value.

3) Once a constant is declared, it cannot be modified or assigned a new value.

Variable:-1) Symbolic names given to values stored in memory and declared with the Dim keyword.

2) Once a Variable is declared, it can be modified or assigned a new value.

For example:-If we have declared a variable named temperature as an integer type, you can store integer values like 72 or 83 in it.84What is the purpose of the CInt function & the CDec Function?=> CInt:- The purpose of the CInt function is to convert to Int data type. CDec:- The purpose of the CDec function is to convert to decimal data type.85 What statement(s) can be used to declare a variable?=> The Dim statement can be used to declare a variable.Example:-Dim state as int

86What is a message box and when should you use one?

Navgujarat BCA Page 91 of 98

Page 92: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

=>Messagebox is an easy way to add multiple forms already built in visual basic .We can also use the messagebox built into the .net framework to display message and accept input from the user. 87 Explain why the MessageBox.Show method has multiple signatures.=> MessageBox.Show method has multiple signature to choose from MessageBox.Show(Text message) MessageBox.Show(Text message, Titlebartext) MessageBox.Show(Text message, Titlebartext, _Messgae boxbuttons) MessageBox.Show(Text message, Titlebartext, _Messgae boxbuttons, Message box icon)88 Why must you use module-level variables if you want to accumulate a running total of transactions?=>Module level variables are accessible from all procedures of a form. 90What is a condition?=> This is preliminary documentation and is subject to change.

Contains type-specific information for effects that are marked as DIEFT_CONDITION.A reference to an array of Dicondition structures for an effect is passed in the lpvTypeSpecificParams member of the Dieffect structure. The number of elements in the array must be either one, or equal to the number of axes associated with the effect.

Definition

Visual Basic Public Structure ConditionComputer# public struct ConditionManaged C++public __value struct ConditionJScript In JScript, you can use structures, but you cannot define your own.

91Explain the purpose of Relational and Logical operators.=> Relational operator:- A relation operator compares operands and returns a logical value based on whether the comparison is true or not. The table below summarizes them:

- <(Less than) –True=If operand1 is less than operand 2. - <=(Less than or equal to)-True= If operand1 is less than or equal to operand 2.- >(Greater than)-True= If operand1 is greater than operand 2- >=(Greater than or equal to)-True= If operand1 is greater than or equal to operand 2- =(Equal to)-True= If operand1 is equal to operand 2- <>(Not equal to)-True= If operand1 is not equal to operand 2- Like=Performs string pattern matching.- Is - True=If two object references refer to the same object. Logical operator:- Logical operator compare Boolean expression and return a Boolean result. In short, logical operator are expression which return

Navgujarat BCA Page 92 of 98

Page 93: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

True or false result over a conditional expression.

- And:- Performs an And operation.- Not:- Reverse the logical value of its operand from True to false and false to true.- Or:- Performs an Or operation.- Xor:- Performs an exclusive or operation. - And also:- Operator A “short circuited “ And operator ;if the first operand is false,the second operand is not tested.- OrElse:- Operator A “short circuited “ Or operator ;if the first operand is true,the second operand is not tested.

94) Explain a Boolean variable test for True and False. Give an example.

=> Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False. Use the keywords True and False to assign one of the two states to Boolean variables.

When numeric data types are converted to Boolean values, 0 becomes False and all other values become True. When Boolean values are converted to numeric types, False becomes 0 and True becomes -1.

95) What is separator bar and how is it created?=>Separator bars are used to group related commands within a menu and make menus easier to read. To add a separator bar as a menu item In the Menu Designer, right-click the location where you want a separator bar, and choose

New Separator. -or-

When setting the Text property (either in the Properties window, in the Menu Designer, or in code) of the menu item, enter a dash (–) to make that menu item a separator bar.

97) Explain the difference between sub procedure and function procedure.=> Sub procedure:- 1) A procedure that does not return a value. 2) In sub procedure we use sub keyword. 3) In sub procedure its ending done with “End sub” Function procedure:- 1) A procedure that returns a value. 2) In function procedure we use Function keyword. 3) In function procedure its ending done with “End function”.

Navgujarat BCA Page 93 of 98

Page 94: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

Questions

1. What are objects and properties? How are they related to each other?

2. What is the purpose of these visual basic file types: .sln,.suo,.vb?3. What is the purpose of the name property of a control?4. What is the purpose of the text property of a button?5. What is the purpose of the text property of a form?6. What is visual basic event? Give example of events?7. What is the purpose of keyboard access keys?8. How can you define access key in your project?9. Explain use of accept button and cancel button properties of the

form10. What is a tooltip?how can you make a tool tip appear?11. Name and give example of the data types of vb.12. What is purpose of cint functions?13. What statements are used to declared variable?14. What is message box and how it is used?15. Explain the relational and logical operators16. How does visual basic compare the text property of a text box?17. List different types of projects in visual basic .net.18. How to add items in combo box at runtime?19. Write The Sequence Of Events When Form Will Be Loaded?20. Give the syntax to create user define data types in vb .net.21. Explain any three control structure of VB .net with example.22. Explain Diff. Module available in VB .net23. Explain Rich Textbox with at least Five Properties & 2 Methods.24. List elements of Visual Basic .net IDE.25. Give the different states in visual basic .net .26. List visual basic .net numeric data types.27. Write syntax to generate context menu.28. Give different types of combo box.29. Explain different string formatting functions with example

Navgujarat BCA Page 94 of 98

Page 95: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

30. Explain List view control with example31. What Is Event Driven Programming?32. What Is Difference Between Module And Class Module?33. What Is Default Property Of Textbox And Combo Box Control?34. When Paint Event Of Form Will Be Called?35. Explain Features Of Visual Basic .net.36. What is use of Preserve keyword?37. Give extension of different files created in VB .net.38. Define property and events.39. What is use of strict, compare and explicit keywords?40. How buttons can be loaded at runtime?41. Create function to find sum of two numbers which will return sum

and take two numbers as parameters.42. Explain scope of variable in visual basic .net.43. List Editions of Visual Basic .net

Explain Fixed Size Array

Practical Questions:1. Create application for notepad which has following menu

a. Filei. New

ii. Openiii. Saveiv. Save asv. Exit

b. Editi. Cut

ii. Copyiii. Paste

c. Formati. Font

ii. Color2. Create application in which there are two list boxes and for command button

which has facility to shift one element or more elements from list1 to list 2 and viceversa.Also there are three command button for each list box to add new item/s, delete selected item/s and to sort item of each list.

3. Create application to format textbox using scroll bar. Use separate scrollbar for each formatting.Formating are as under

a. Font size(increase and decrease)b. Foreground colorc. Back ground color

4. Create class library for calculator. Which has two properties for operand1 and operand2.it should have four methods as add ,delete, subtract and multiply.

Navgujarat BCA Page 95 of 98

Page 96: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

5. Create application to display greetings in message box.

6. Create application to find area of square ,circle, Triangle. Use two

textbox to enter values and three command buttons.

7. Create applications for calculator.

8. Create application to find simple interest and compound interest.

9. Create application to change background color and for ground

color of textbox by selecting color from list box.

10. Create application to display date and time in text box and

display appropriate greeting . Ex : Good morning , good noon etc.

11. Create application to display multiplication table of any no

entered from text box.

12. Create application to find reverse length of string and also

find that string is palindrome or not.

13. Create application to find intital of name . Ex : Dr.

Prathamesh Ramaniklal Vyas . Ans : Dr. P.R. Vyas.

14. Create application for payroll that is enter name and basic

salary of employee and create whole salary slip.

15.Create application for notepad.Which have following facilities.1. Menubar (File,Edit,Format)

16.Create application to change background color of button by scrolling the scroll bar.

17.Create application to set the indent of the text using slider.

18.Create ActiveX application for stopwatch.

19.Create form which will work like font foramating dilog box.

20.Create ActiveX control for the animation of background color.

21.Create application for Phone Directory Phone(ph_no, name, address, city, district)

Navgujarat BCA Page 96 of 98

Page 97: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

1. Addition, deletion and modification of any entry.

22.Create application for Phone Directory Phone(ph_no, name, address, city, district)

1. Make search criteria based on name and phone number.2. Create report of that search.

23.Create application for the cinema ticket booking system.Cinema(film_id, film_name, th_id, ShowTime,)book(ticket_id, film_id, rate, book)1.Create search form in which user has to give the choice for film in combobox. It should display the ticket status of that film in datagrid.

24.Create application for the cinema ticket booking system.Cinema(film_id, film_name, th_id, ShowTime,)book(ticket_id, film_id, rate, book)

1. create form to book the ticket.

25.Create appliction for train scheduling Train(train_no,train_name,source,dest)Schedule(train_no,date,time)1.make search for the train timings between two dates

26.Create appliction for train scheduling Train(train_no,train_name,source,dest)Schedule(train_no,date,time)

1.create the trainwise report

27.Create inventory system for the small vendor.Item(item_id,item_name,cp,spstock)Sale(item_id,date,quantity)

1.create itemwise search form.result should be displayed in flexgrid.2.generate report for the daywise sale.

28.create student information system.Student(grno,stud_name,dob,age,lastschool,fname,address,city,phone)

Navgujarat BCA Page 97 of 98

Page 98: Dotnet theory

Advanced Visual and Windows Programming(BCA-205)

1.create admission form of the student. Grno must be generated by the system.2.generate report of the student for specific year.

29.Create application for online examination for any subject.

1.Give result at the end of the test2.Generate report of the userwise test result.

30.Create an application for a bank.ACC_DETAIL(AC_NO,DATE,O_BAL,C_BAL)

Create form for withdraw money from bank.Create report for daywise transaction.

Navgujarat BCA Page 98 of 98