Sie sind auf Seite 1von 223

R4R provide basic VB.Net Tutorials concept with VB.Net Examples . Through R4R you can develop VB.

Net programming concept. R4R provide VB.Net Interview Questions with answers.R4R provide VB.Net Languages study materials in easy way.

VB.Net Tutorials
1.1 1.2 VB.Net Basic Tutorial ASP.Net Basic Tutorial (VB.Net Based)

VB.Net Interview Questions with Answers


2.1 2.2 2.3 2.4 VB.Net Subjective Questions with Answers VB.Net Interview Questions with Answers VB.Net Objective Questions And Answers FAQS

Introduction of VB .Net
Visual Basic .NET (VB.NET) is an object-oriented programming language that can be considered as an evolution of the classic Visual Basic (VB) which is implemented on the .NET Framework. Visual Basic .Net was developed to make Web services applications easier to develop. According to Microsoft, VB .NET was reengineered, rather than released as VB 6.0 with added features, to facilitate making fundamental changes to the language. VB.NET is the first fully object-oriented programming (OOP) version of Visual Basic, and as such, supports OOP concepts such as abstraction, inheritance, polymorphism, and aggregation.

History of VB .Net
Visual Basic .NET was released alongside Visual C# and ASP.NET in 2002.Visual Basic .NET should be considered as just another version of Visual Basic 6.0.Microsoft supplies an automated VB6-to-VB.NET converter with Visual Studio .NET, which has improved over time, but it cannot convert all code, and almost all non-trivial programs will need some manual effort to compile. Most will need a significant level of code refectory to work optimally. Visual Basic programs that are mainly algorithmic in nature can be migrated with few difficulties.

Versions of VB .Net
Version Visual Basic .NET (VB 7) Visual Basic .NET 2003 (VB 7.1) Visual Basic 2005 (VB 8.0) Visual Basic 2008 (VB 9.0) Visual Basic 2010 (VB 10.0) February 2002 2003 2005 19 November 2007 April 2010 Date

Important features of VB .Net Fully object oriented programming. Designed to .NET Framework. Structured error handling capabilities. Inherent support for XML & Web Services. Better windows applications with Windows Forms. Console capabilities of VB.NET. Web capabilities with Web Forms. Better database programming approach with ADO. NET. Interpretability with other .NET complied languages. Immense power of tools & controls (including Server Controls).

Architecture of VB.NET

Advantage of VB .Net VB.NET provides managed code execution that runs under the Common Language Runtime (CLR), resulting in robust, stable and secure applications. All features of the .NET framework are readily available in VB.NET. VB.NET uses XML to transfer data between the various layers in the DNA Architecture i.e. data are passed as simple text strings. Powerful Windows-based Applications. Building Web-based Applications. Simplified Deployment. Powerful, Flexible, Simplified Data Access. Improved Coding. Direct Access to the Platform.

Full Object-Oriented Constructs. XML Web Services. Mobile Applications. COM Interoperability. Reuse Existing Investments. Upgrade Wizard

Disadvantage of VB .Net Cannot handle pointers directly Large Talent Pool Intermediate Language (IL) compilation Just-In-Time (JIT) compiler Large Libraries

VB.Net Basic Tutorial

1. Net Framework Architecture 2. Control Statements 3. Arrays, Indexer and Collections 4. Inheritance and Polymorphism 5. Attributes 6. Delegates and Events 7. Exception Handling 8. Threading 9. Introduction to Visual Studio 10. Introducing Windows Forms 11. Button Control 12. Label and Link Label 13. TextBox control 14. Radio Button and CheckBox Controls 15. GroupBox Control 16. Rich TextBox Control 17. ListBox Controls 18. ComboBox Controls 19. StatusBar Control 20. Tabcontrol Control 21. NotifyIcon Control 22. Masked Textbox 23. Window Media Player 24. Dialog Controls 25. Printing Controls 26. Data Controls 27. Error Provider Control 28. Help Provider 29. Flow Layout Panel

30. Table Layout Panel 31. Panel Control 32. Split Container Control 33. DateTimePicker and Month Calendar 34. NumericUpDown Control 35. ProgressBar and Timer Control 36. ToolTip Control 37. TreeView Control 38. Menus and ToolBar Controls 39. Background Worker Control 40. Creating Slice Chart in windows using VB.Net 41. Socket 42. Creating Bar Chart in windows using VB.Net 43. dll 44. Access IP Address of LAN Connected Computers 45. IP Address of Websites in VB.Net application 46. Synchronization in VB.Net 47. Creating Word document using VB.Net 48. How to Add Manually CheckBox in VB.Net 49. How to Change The Color of Specific Word in Rich textbox using

VB.Net 50. Reading/Writing/Appending a Text File, Using VB.Net 51. How to Find Max Value of X, Y ,Z From Text file Using VB.Net 52. Multiple Colored Texts in RichTextBox using VB.Net 53. Storing Database Connection Strings in App.Config
.Net Frameworks Architecture

.Net is not an Operating System. It is a IDE. It provides some functionality for the programmers to build their solution in the most constructive and intellegent way ever. Just to tell you the truth, most of the codes in .Net environment resembles with the JAVA coding as if some people coming from Java would find it as to their native language. .NET is a Framework that loads into your operating system, which you need not to load in the later versions of windows like Windows 2003 server or Just a new release of Windows Vista. As it is going to be added as a component in the next generation of windows. Now, What is the .Net all about? Well, Its a framework that supports Common Language Runtime (CLR). As the name suggests, Common Language Runtime will be something that will run a native code for all the programming languages provided within the Architecture. Another feature of .net is language independence, to tell you about language Independence, .Net is not at all efficient in that. Just Microsoft built their own version of languages like C+ +, J# (for Java), C#, VB etc that can communicate between each other. After all J#, even if they resembles with JAVA is not purely Java.. Thus, the word may look to you somewhat fake. Now what is the most prospective part of .NET? Now, with the growing Internet, ASP. NET may be the most important part of .NET technology. Well, ASP. NET has a new technology where the controls reside server side. You don't bother to use traditional client side controls. In .NET technology as there is a provision of runtime building of machine codes, a web server can directly compile and transmit codes to the browser during runtime. This is , I think the most approved and widely accepted part of .NET. NEW things of .NET? well, during the last two years , Microsoft is constantly changing the .NET technology, that may not be good for a settled programmer. Well, first of all, in .NET 2003 Microsoft changed some features and also adds some new things. Well, new things are good, but changing the existing in such a quick succession is not at all good from programmers point of view. Again, in 2005, Microsoft publishes the new release of VISUAL

STUDIO.NET 8 . This is a completely new environment. It have new releases of controls, the IDE is also different. That's not what we all wanted as a programmer. What do you say? Now, Microsoft is also increasing its scope.. One of the most important feature that is just now introduced is AJAX. Well, the name is what can be said as Asynchronous Java Script with XML.

.Net Frameworks Architecture

The if Statement
if statement is used to take different paths of logic, depending on the conditions. Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If TextBox1.Text >= 80 Then MessageBox.Show("Got Higher First Class ") ElseIf TextBox1.Text >= 60 Then MessageBox.Show("Got First Class ") ElseIf TextBox1.Text >= 40 Then MessageBox.Show("Just pass only") Else MessageBox.Show("Failed") End If End Sub End Class The switch Statement Another form of selection statement is the switch statement, which executes a set of logic depending on the value of a given parameter. The types of the values a switch statement operates on can be booleans, enums, integral types, and strings. The while Loop While loop is used to check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true. Syntax:while (<boolean expression>) { <statements> } When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code. Public Class Form1 Private Sub Button1_Click(ByVal sender As

System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer = Integer.Parse(TextBox1.Text.ToString()) While i < 10 MessageBox.Show("I am in While statement ") i += 10 End While End Sub End Class The do-while Loop A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time. The for Loop It works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold three sections separated by semicolons (<initializer list>; <boolean expression>; <iterator list>) { <statements> }. Module Module1 Sub Main() For i As Integer = 0 To 19 If i = 10 Then Exit For End If If i Mod 2 = 0 Then Continue For End If Console.Write("{0} ", i) Next Console.WriteLine() End Sub End Module Foreach Statement: The foreach statement is new to the C family of languages; it is used for looping through the elements of an array or a collection. Module Module1 Sub Main() Dim num As Integer() = New Integer() {0, 1, 2, 3, 4, 5, _ 6, 7, 8} For Each i As Integer In num System.Console.WriteLine(i)

Next End Sub End Module

Array
An array is the collection of similar type of objects. Array in VB.net is different for the array of C++ and other languages because they are objects. This provides them useful methods and property. Arrays allow a group of elements of a particular type to be stored in a contiguous block of memory. Array types derive from System.Array and are declared in VB.net using brackets (()). Syntax: datatype [] array-name; e.g. Dim books As Integer()()() = New Integer(2)()() {};

Multidimensional Array:
Multidimensional Arrays of two types Rectangular Array and Jagged Array Rectangular Array represents n-dimensional blocks. e.g.- Dim age As Integer(,,) = New Integer(16, 19, 33) {} Jagged Arrays are arrays of arrays. Dim books As Integer()()() = New Integer(2)()() {} For i As Integer = 0 To 2 books(i) = New Integer(3)() {} For j As Integer = 0 To 3 books(i)(j) = New Integer(4) {} Next Next Indexer: Indexers are usually known as smart array in VB.net.It is used for treating object as an array.Defining an indexer in VB.net is much like same as defining properties. Or we can say that an indexer is a member that enables an object to be indexed in the same way as an array. Collections: Collections are the enumerable data structure in VB.net that can be assessed using indexes or keys. Types of collections in VB.net are given belowSystem.Collections namespace This provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it. The interfaces that are defined in this namespace include: IEnumerable IEnumerator ICollection IList IDictionary System.Collections.Stack

System.Collections.Queue Both are derived from ICollection Interface. The collections that inherit the IDictionary interface include: System.Collections.SortedList System.Collections.Hashtable The IList interface represents collections that only have value. The following are the classes that extend this interface. System.Array System.Collections.ArrayList System.Collections.Specialized.StringCollection

Concrete Collection Classes: ArrayList class- This works by maintaining an internal array of objects that is replaced with a larger array when it reaches its capacity of elements. BitArray class- It is a dynamically sized array of Boolean values. It is more memoryefficient than a simple array of bools because it uses only one bit for each value. Hashtable class- A Hashtable is a standard dictionary (key/value) data structure that uses a hashing algorithm to store and index values efficiently. Queue class- A Queue is a standard first-in, first-out (FIFO) data structure, providing simple operations to enqueue, dequeue, peek, etc. SortedList class-A SortedList is a standard dictionary data structure that uses a binarychop search to index efficiently. Stack class- A Stack is a standard last-in first-out (LIFO) data structure. StringCollection class- A StringCollection is a standard collection data structure for storing strings.

Inheritance
In VB.Net, the specialization relationship is generally implemented by using inheritance. Inheritance is also provides the reusability, or we can say that extracts some features from one class to another class. Class Bird Public Sub New() Console.WriteLine("Bird constructor") End Sub Public Sub Greet() Console.WriteLine("Bird says Hello") End Sub Public Sub Talk() Console.WriteLine("Bird talk") End Sub Public Overridable Sub Sing() Console.WriteLine("Bird song") End Sub End Class Class Peacock Inherits Bird Public Sub New()

Console.WriteLine("Peacock constructor") End Sub Public Shadows Sub Talk() Console.WriteLine("Peacock talk") End Sub Public Overrides Sub Sing() Console.WriteLine("Peacock song") End Sub End Class Dim a1 As New Bird() a1.Talk() a1.Sing() a1.Greet() Dim a2 As Bird = New Peacock() a2.Talk() a2.Sing() a2.Greet() Types of Inheritance: In Object Oriented Programming concept there are 3 types of inheritances. 1. Single Inheritance, 2. Multiple Inheritance 3. Multilevel Inheritance Single Inheritance: Public Class A End Class Public Class B Inherits A End Class Multiple Inheritance: Public Class A End Class Public Class B End Class Public Class C Inherits A Inherits B End Class Multilevel Inheritance: Public Class A End Class

Public Class B Inherits A End Class Public Class C Inherits B End Class In the above three types VB.net don't proved Multiple Inheritance. As there is conflict of multiple override methods in base classes (say A, B in above example) As in Place VB.net give another feature called Interfaces using interfaces you can achieve multiple Inheritance feature. Polymorphism Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details. Creating Polymorphic Types: For creating polymorphism there are two steps1. Create a base class with virtual methods. 2. Create derived classes that override the behavior of the base classs virtual methods. To create a method in a base class that supports polymorphism, mark the method as virtual. Example. Public Class BaseClass Public Overridable Sub DoWork() End Sub Public Overridable ReadOnly Property WorkProperty() As Integer Get Return 0 End Get End Property End Class Public Class DerivedClass Inherits BaseClass Public Overrides Sub DoWork() End Sub Public Overrides ReadOnly Property WorkProperty() As Integer Get Return 0 End Get End Property End Class

Attributes

Attributes contains a powerful method of associating declarative information with VB.Net code for types, methods, properties. Once associated with a program entity, the attribute can be queried at run time and used in any number of ways. Uses of Attributes: Associating help documentation with program entities (through a Help attribute). Associating value editors to a specific type in a GUI framework (through a Value Editor attribute).

<AttributeUsage(AttributeTargets.All)> _ Public Class HelpAttribute Inherits System.Attribute Public ReadOnly Url As String Public Property Topic() As String ' Topic is a named parameter Get Return m_topic End Get Set End Set End Property m_topic = value

Public Sub New(url As String) ' url is a positional parameter Me.Url = url End Sub Private m_topic As String End Class When do we need attributes ? 1. The System.ObsoleteAttribute attribute that we have just described is a good example of how an attribute is used by the compiler, certain standard attributes which are only destined for the compiler are not stored in the assembly. 2. An attribute can be consumed by the CLR during execution. For example the .NET Framework offers the System.ThreadStaticAttribute attribute. When a static field is marked with this attribute the CLR makes sure that during the execution, there is only one version of this field per thread. 3. An attribute can be consumed by a debugger during execution. Hence, the System.Diagnostics.DebuggerDisplayAttribute attribute allows personalizing the display of an element of the code the state of an object for example) during debugging.

Delegate
A delegate in VB language allows us to reference a method. If we are using a C or C++ then we would sound familiar because a delegate because it

is basically a function pointer. Delegates have other uses in addition to event handling. Delegate maintains three important pieces of information : 1. The name of the method on which it make calls. 2. Any argument (if any) of this method. 3. The return value (if any) of this method.

What is a Function Pointer? Function Pointers are pointers, i.e. variables, which point to the address of a function.

Types of Delegate
Delegates are of two types 1.Single Cast delegate public delegate <return type> <delegate name>(parameters) 2.Multi Cast delegate public delegate void <delegate name>(parameters) Advantage of using Delegate Dynamic binding can be done by using delegate because we can call more than one methods at a time dynamically by calling the delegate in which the methods is defined. Example Namespace delgnew Public Delegate Function Delg(x As Integer, y As Integer) As Integer Public Class Math Public Shared Function Add(x As Integer, y As Integer) As Integer Return x + y End Function Public Shared Function Multiply(x As Integer, y As Integer) As Integer Return x * y End Function End Class Class Fun Private Shared Sub Main(args As String()) Dim del1 As New Delg(AddressOf Math.Add) Dim add1 As

Integer = del1(7, 7) Console.WriteLine("7 + 7 = {0}" & vbLf, add1) Dim del2 As New Delg(AddressOf Math.Multiply) Dim multiply1 As Integer = del2(7, 7) Console.WriteLine("7 * 7 = {0}", multiply1) Console.ReadLine() End Sub End Class End Namespace

Static Delegates Denoting static field is meaning that it will not be modified. You can invoke delegates without declaring a local delegate instance. Just pass in the static delegate of the class. Delegates as Properties The problem with static delegates is that they must be instantiated whether or not they are ever used. Event An event might be a button push, a menu selection in short we can cay that something happens and you must respond to it. You cannot predict the order in which events will arise. For example- when you click a button, it might raise the Click event. When you add to a drop-down list, it might raise a List Changed event. Defining Event Class Eventtest Public Custom Event myfun As EventHandler AddHandler(ByVal value As EventHandler) Console.WriteLine("Event Fired") End AddHandler RemoveHandler(ByVal value As EventHandler) Console.WriteLine("Controlled") End RemoveHandler End Event Private Shared Sub Main()

Eventtest()

Dim et As Eventest = New

et.myfun += New EventHandler(et.DoNothing) et.myfun -= Nothing End Sub Private Sub DoNothing(sender As Object, e As EventArgs) End Sub End Class An event allows a class (or other object) to send notifications to other classes (or objects) that something has occurred. In simple terms an event is the outcome of a specific action. If you have developed programmers in graphical user interfaces (GUI) then you are very familiar with Event handling. When a user interacts with a GUI control (e.g., clicking a button on a form), one or more methods are executed in response to the above event. Events can also be generated without user interactions. Event handlers are methods in an object that are executed in response to some events occurring in the application.

What is Exception?
The exceptions are anomalies that occur during the execution of a program. Exception handling is a mechanism in .NET framework to detect and handle run time errors. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. In VB.Net there are three keywords Try, Catch and Finally for handling exceptions. In try block statements it might throw an exception whereas catch handles that caused by try block if one exists. The finally block is used for doing any clean up process. The statement in finally block always executes. e.g.

' this can cause an exception. Try ' for handling the exception. Catch x As Type 'this will execute. Finally End Try

Handling Exceptions
In catch block, if don't use a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch

block with an Exception type parameter to catch all exceptions happened inside the try block. Since in VB.net, all exceptions are directly or indirectly inherited from the Exception class. e.g. Class newexp Public Shared Sub Main() Dim a As Integer = 0 Dim div As Integer = 0 Try div = 100 \ a Console.WriteLine("This will not print") Catch Console.WriteLine("oException") End Try Console.WriteLine("Result is {0}", div) End Sub End Class Exceptions Classes Following are some common exception classes. SystemException- This exception means a failed run-time check used as a base class for other. AccessException- This exception means failure to access a type member, such as a method or field. ArgumentException- This exception means an argument to a method was invalid. ArgumentNullException- This exception means a null argument was passed to a method that doesn't accept it. ArgumentOutOfRangeException-This exception means argument value is out of range. ArithmeticException- This exception means arithmetic over or underflow has occurred. ArrayTypeMismatchException- This exception means attempt to store the wrong type of object in an array. BadImageFormatException- This exception means image is in the wrong format. CoreException- This exception means base class for exceptions thrown by the runtime. DivideByZeroException- This exception means an attempt was made to divide by zero. FormatException- This exception means the format of an argument is wrong. IndexOutOfRangeException- This exception means an array index is out of bounds. InvalidCastExpression- This exception means an attempt was made to cast to an invalid class. InvalidOperationException- This exception means a method was called at an invalid time.

MissingMemberException- This exception means an invalid version of a DLL was accessed. NotFiniteNumberException- This exception means a number is not valid. NotSupportedException- This exception means indicates that a method is not implemented by a class. NullReferenceException- This exception means attempt to use an unassigned reference. OutOfMemoryException- This exception means not enough memory to continue execution. StackOverflowException- This exception means a stack has overflow.

What is thread ?
Threads are typically created when you want a program to do two things at once.

Starting Threads
The simplest way to create a thread is to create a new instance of the Thread class. The Thread constructor takes a single argument: a delegate type. The CLR provides the ThreadStart delegate class specifically for this purpose, which points to a method you designate. This allows you to construct a thread and to say to it "when you start, run this method." The ThreadStart delegate declaration is: Public Delegate Sub ThreadStart()

Example for Creating Thread:


Imports System.Threading Public Class CreatingThread Private Shared Sub Main(args As String()) Dim MyThread As New Thread(New ThreadStart(ThreadProc)) MyThread.Start() MyThread.Join()

End Sub Protected Shared Sub ThreadProcess() For i As Integer = 0 To 99 Console.WriteLine(i) Next End Sub End Class

Creating a Thread of Execution:


Imports System.Threading Class MyThread Public count As Integer Private thrdName As String Public Sub New(name As String) count = 0

thrdName = name End Sub Public Sub run() Console.WriteLine(thrdName & " starting.") Thread.Sleep(500) Console.WriteLine("In " & thrdName & ", count is " & count) count += 1 Loop While count < 10 Console.WriteLine(thrdName & " terminating.") End Sub End Class Public Class MultiThread Public Shared Sub Main() Console.WriteLine("Main thread starting.") Dim mt As New MyThread("Child #1") Dim newThrd As New Thread(New ThreadStart(AddressOf mt.run)) newThrd.Start() Do Console.Write(".") Thread.Sleep(100) Loop While mt.count <> 10 Console.WriteLine("Main thread ending.") End Sub End Class Do

Joining Threads
To join thread1 (t1) onto thread2 (t2), write: t2.Join() Joining the current thread to each thread in the collection in turn:

For Each myThread As Thread In myThreads myThread.Join() Next Console.WriteLine("All my threads are done.")

Create multiple threads of execution


Imports System.Threading Class MyThread

Public count As Integer Public thrd As Thread Public Sub New(name As String)

count = 0

thrd = New Thread(New ThreadStart(AddressOf Me.run)) thrd.Name = name

thrd.Start() End Sub Private Sub run()

" starting.")

Console.WriteLine(thrd.Name &

Do

Thread.Sleep(500)

Console.WriteLine("In " & thrd.Name & ", count is " & count)

count += 1

Loop While count < 10

Console.WriteLine(thrd.Name & " terminating.") End Sub End Class Public Class MoreThreads Public Shared Sub Main() Console.WriteLine("Main thread starting.") Dim mt1 As New MyThread("Child #1") Dim mt2 As New MyThread("Child #2") Dim mt3 As New MyThread("Child #3") Do

Console.Write(".")

Thread.Sleep(100) Loop While mt1.count < 10 OrElse mt2.count < 10 OrElse mt3.count < 10 Console.WriteLine("Main thread ending.") End Sub End Class

Suspending Threads
To cause your thread to sleep for one second, you can invoke the static method of Thread, Sleep, which suspends the thread in which it is invoked: Thread.Sleep(1000)

Killing Threads
For killing a thread Abort( ) method is used. This causes a ThreadAbortException exception to be thrown, which the thread can catch, and thus provides the thread with an opportunity to clean up any resources it might have allocated.

Example for Suspending, resuming, and stopping a thread: Imports System.Threading Class MyThread Public thrd As Thread Public Sub New(name As String) thrd = New Thread(New ThreadStart(AddressOf Me.run)) thrd.Name = name thrd.Start() End Sub Private Sub run() Console.WriteLine(thrd.Name & " starting.") For i As Integer = 1 To 1000 Console.Write(i & " ") If (i Mod 10) = 0 Then Console.WriteLine() Thread.Sleep(250) End If Next Console.WriteLine(thrd.Name & " exiting.") End Sub End Class

Public Class SuspendResumeStop Public Shared Sub Main() Dim mt1 As New MyThread("My Thread") Thread.Sleep(1000) ' let child thread start executing mt1.thrd.Suspend() Console.WriteLine("Suspending thread.") Thread.Sleep(1000) mt1.thrd.[Resume]() Console.WriteLine("Resuming thread.") Thread.Sleep(1000) mt1.thrd.Suspend() Console.WriteLine("Suspending thread.") Thread.Sleep(1000) mt1.thrd.[Resume]() Console.WriteLine("Resuming thread.") Thread.Sleep(1000) Console.WriteLine("Stopping thread.") mt1.thrd.Abort() mt1.thrd.Join() ' wait for thread to terminate Console.WriteLine("Main thread terminating.") End Sub End Class

Synchronization Synchronization is provided by a lock on the object, which prevents a second thread from barging in on your object until the first thread is finished with it.

Microsoft Visual Studio

Visual Studio is an integrated development environment (IDE) developed by Microsoft. It can be used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all platforms supported by Microsoft Windows, Windows Mobile, Windows CE.

Architecture
It does not support any programming language, solution or tool intrinsically. Instead, it allows plugging in various types of functionality, that is coded as a VSPackage. The IDE provides three services: SVsSolution, which provides the ability to enumerate projects and solutions; SVsUIShell, which provides windowing and UI functionality (including tabs, toolbars and tool windows) SVsShell, which deals with registration of VSPackages. In addition, the IDE also manages for coordinating and enabling communication between services. All editors, designers, project types and other tools are implemented as VSPackages. Visual Studio uses COM to access the VSPackages. The Visual Studio SDK also includes the Managed Package Framework (MPF), which is a set of managed wrappers around the COM-interfaces that allow the Packages to be written in any CLI compliant language. However, MPF does not provide all the functionality exposed by the Visual Studio COM interfaces. The services can then be consumed for creation of other packages, which add functionality to the Visual Studio IDE.

Features of Microsoft Visual Studio

Code editor: Code editor that supports syntax highlighting and code completion using IntelliSense for not only variables, functions and methods but also language constructs like loops and queries. Debugger: It works both as a source-level debugger and as a machine-level debugger. It works with both managed code as well as native code and can be used for debugging applications written in any language supported by Visual Studio. Designer: It includes a host of visual designers to aid in the development of applications. These tools includes Windows Forms Designer: It includes a palette of UI widgets and controls (including buttons, progress bars, labels, layout containers and other controls) that can be dragged and dropped on a form surface. WPF(Windows Presentation Foundation) Designer: It is used to author user interfaces targeting Windows Presentation Foundation. It supports all WPF functionality including data binding and automatic layout management. Web designer/development: It is used for developing ASP.NET applications and supports HTML, CSS and JavaScript. It uses a code-behind model to link with ASP.NET code. From Visual Studio 2008 onwards, the layout engine used by the web designer is shared with Microsoft Expression Web.

Class designer: The Class Designer can generate VB.NET code outlines for the classes and methods. It can also generate class diagrams from hand-written classes. Data designer: The data designer can be used to graphically edit database schemas, including typed tables, primary and foreign keys and constraints. It can also be used to design queries from the graphical view. Mapping designer: The mapping designer is used by LINQ to SQL to design the mapping between database schemas and the classes that encapsulate the data.

Other tools ToolBox Explorer

Open Tabs Browser: It is used to list all open tabs and to switch between them. It is invoked using CTRL+TAB. Properties Editor: It is used to edit properties in a GUI pane inside Visual Studio.

Object Browser: It can be used to browse the namespaces (which are arranged hierarchically) in managed assemblies.

Solution Explorer: It is used to manage and browse the files in a solution.

Team Explorer: It is used to integrate the capabilities of Team Foundation Server, the Revision Control System into the IDE (and the basis for Microsoft's CodePlex hosting environment for open source projects). In addition to source control it provides the ability to view and manage individual work items (including bugs, tasks and other documents) and to browse TFS statistics. Data Explorer: It is used to manage databases on Microsoft SQL Server instances. Server Explorer: It tool is used to manage database connections on an accessible computer.

Included products Microsoft Visual C++: It is Microsoft's implementation of the C and C++ compiler and associated languages-services and specific tools for integration with the Visual Studio IDE. Microsoft Visual C#: Microsoft's implementation of the C# language, targets the .NET Framework, along with the language services that lets the Visual Studio IDE support C# projects. Microsoft Visual Basic: Microsoft's implementation of the VB.NET language and associated tools and language services. It was introduced with Visual Studio .NET (2002).

Creating Windows Application


For creating a new project you need to first load Visual Studio .NET and select Windows Application as in Figure below . Type the name of the project below along with selecting the desired location to store your files.

Designing The Interface: We are going to design a simple application for adding values in List Box from from textbox input by the user, for this will need to add the following items onto your form. GroupBox Label ComboBox Textbox Button ListBox

Adding The Code: When this form loads we need to populate the ComboBox with the appropriate values. Add the following code by clicking on the form on the outside of the groupBox. You should see something like this: write this code on Form Load EventPrivate Sub Form1_Load(sender As Object, e As EventArgs) comboBox1.Items.Add("Dr.") comboBox1.Items.Add("Er.") comboBox1.Items.Add("Mr.") comboBox1.Items.Add("Mrs.") comboBox1.Items.Add("Ms.") comboBox1.Focus() End Sub Double-click on the OK button and add the following code: Private Sub button1_Click(sender As Object, e As EventArgs) listBox1.Items.Add((comboBox1.Text + " " + textBox1.Text & " ") + textBox2.Text) textBox1.Text = "" textBox2.Text = ""

comboBox1.Text = "" comboBox1.Focus() End Sub When we want to allow the user to clear all fields entered into the listBox, we will need to go back like we did above to the visual designer and double-click on the Clear List button, this should again switch to a code view and allow you to add the following codePrivate Sub button2_Click(sender As Object, e As EventArgs) listBox1.Items.Clear() comboBox1.Focus() End Sub And finally we want to allow the user to be able to close the application when they want. To show you another way to allow the user to close the program aside from that catchy X in the upper right-hand corner, I have provided a button entitled Close. Private Sub button3_Click(sender As Object, e As EventArgs) Me.Dispose() End Sub Controls System.Windows.Forms.Control class This class defines the basic functionality of the controls, which is why many properties and events in the controls. Some controls, named custom or user controls, derive from another class: System.Windows.Forms.UserControl. This class is itself derived from the Control class and provides the functionality we need to create controls ourselves. Properties All controls have a number of properties that are used to manipulate the behavior of the control. The base class of most controls, Control, has a number of properties that other controls either inherit directly or override to provide some kind of custom behavior.

Name
Anchor BackColor Bottom

Availability
Read/Write Read/Write

Description
It tells how control behaves when its container is resized. about background color of a control. You can specify the distance from the top of the window to the bottom of the control. This is not the same as specifying the height of the control. by this property you can make a control dock to the edges of a window. Enabled to true usually means that the control can receive input from the

Read/Write Read/Write Read/Write

Dock Enabled

ForeColor Height Left Name Parent Right TabIndex TabStop

Read/Write Read/Write Read/Write Read/Write Read/Write Read/Write Read/Write Read/Write

Tag

Read/Write

Top Visible Width Events

Read/Write Read/Write Read/Write

user. Setting Enabled to false usually means that it cannot. foreground color of the control. distance from the top to the bottom of the control. left edge of the control relative to the left edge of the window. name of the control. This name can be used to reference the control in code. parent of the control. right edge of the control relative to the left edge of the window. number the control has in the tab order of its container. Specifies whether the control can be accessed by the Tab key. This value is usually not used by the control itself, and is there for you to store information about the control on the control itself. When this property is assigned a value through the Windows Form designer, you can only assign a string to it. The top edge of the control relative to the top of the window. Specifies whether or not the control is visible at runtime. width of the control.

When a user clicks a button or presses a button, you as the programmer of the application, want to be told that this has happened. To do so, controls use events. The Control class defines a number of events that are common to the controls we'll use in this chapter.

Name

Description

MouseMove Occurs continually as the mouse travels over the control. Occurs when the mouse pointer is over a control and a mouse button MouseUp is released. Occurs when a control is clicked. In some cases, this event will also occur when Click a user presses Enter. Occurs when a control is double-clicked. Handling the Click event on some DoubleClick controls, such as the Button control will mean that the DoubleClick event can never be called. Occurs when a drag-and-drop operation is completed, in other words, when an DragDrop object has been dragged over the control, and the user releases the mouse button.

DragEnter DragLeave DragOver

Occurs when an object being dragged enters the bounds of the control. Occurs when an object being dragged leaves the bounds of the control. Occurs when an object has been dragged over the control. Occurs when a key becomes pressed while the control has focus. This event KeyDown always occurs before KeyPress and KeyUp. Occurs when a key becomes pressed, while a control has focus. This event always occurs after KeyDown and before KeyUp. The difference between KeyPress KeyDown and KeyPress is that KeyDown passes the keyboard code of the key that has been pressed, while KeyPress passes the corresponding char value for the key. Occurs when a key is released while a control has focus. This event always KeyUp occurs after KeyDown and KeyPress. Occurs when a control receives focus. Do not use this event to perform GotFocus validation of controls. Use Validating and Validated instead. Occurs when a control looses focus. Do not use this event to perform validation LostFocus of controls. Use Validating and Validated instead. Occurs when the mouse pointer is over a control and a mouse button is MouseDown pressed. This is not the same as a Click event because MouseDown occurs as soon as the button is pressed and before it is released. Paint Occurs when the control is drawn. This event is fired when a control with the CausesValidation property set to true Validated is about to receive focus. It fires after the Validating event finishes and indicates that validation is complete. Fires when a control with the CausesValidation property set to true is about to Validating receive focus. Note that the control which is to be validated is the control which is losing focus, not the one that is receiving it.

The Button Control


The button control exists on just about any Windows dialog you can think of. A button is primarily used to perform three kinds of tasks: For closing a dialog with a state (for example, OK and Cancel buttons) For performing an action on data entered on a dialog (for example clicking Search after entering some search criteria) For opening another dialog or application (for example, Help buttons) Properties of Button Control

Name
FlatStyle

Availability
Read/Write

Description
If you set the style to PopUp, the button will appear flat until the user moves the mouse pointer over it. When that happens, the button pops up to its normal 3D look. Enabled property to false means that the button becomes grayed out and nothing happens when you click it.

Enabled

Read/Write

Image

Read/Write

ImageAlign Read/Write

Allow you to specify an image (bitmap, icon etc.), which will be displayed on the button. With this property, you can set where the image on the button should appear.

Button Events

The most used event of a Button is the Click event. This occurs whenever a user clicks the button, by which we mean pressing the left mouse button and releasing it again while over the button. This means that if you left-click on the button and then draw the mouse away from the button before releasing it the Click event will not be raised. Also, the Click event is raised when the button has focus and the user press Enter. If you have a button on a form, you should always handle this event.

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Label1.Text = "You have clicked the button!!!" End Sub End Class

Label and Link Label


The label is a simple control with one purpose only: to present a caption or short hint to explain something on the form to the user. Visual Studio.NET includes two label controls that are able to present them selves to the user in two distinct ways: Label, the standard Windows label LinkLabel, a label like the standard one (and derived from it), but presents itself as an internet link (a hyperlink)

The TextBox Control


Text boxes should be used when you want the user to enter text that you have no knowledge of at design time (for example the name of the user). The primary function of a text box is for the user to enter text, but any characters can be entered, and it is quite possible to force the user to enter numeric values only. Properties of TextBox

Name

Availability

Description
When a control that has this property set to true is about to receive focus, two events are fired: Validating and Validated. You can handle these events in order to validate data in the control that is losing focus. This may cause the control never to receive focus. The related events are discussed below. A value indicating if the TextBox changes the case of the text entered. The possible values are: q Lower: All text entered into the text box is converted lower case.

CausesValidation Read/Write

CharacterCasing Read/Write

q Normal: No changes are made to the text. q Upper: All text entered into the text box is converted to upper case. A value that specifies the maximum length in characters of any text, entered into the TextBox. Set this value to zero it the maximum limit is limited only by available memory. Indicates if this is a Multiline control. A Multiline control is able to show multiple lines of text. Specifies if a password character should replace the actual characters entered into a single line textbox. If the Multiline property is true then this has no effect. A Boolean indicating if the text is read only. Specifies if a multilane text box should display scrollbars. The text that is selected in the text box. The number of characters selected in the text. If this value is set to be larger than the total number of characters in the text, it is reset by the control to be the total number of characters minus the value of SelectionStart. The start of the selected text in a text box. Specifies if a multiline text box should automatically wrap words if a line exceeds the width of the control.

MaxLength

Read/Write

Multiline

Read/Write

PasswordChar ReadOnly ScrollBars SelectedText

Read/Write Read/Write Read/Write Read/Write

SelectionLength Read/Write

SelectionStart WordWrap

Read/Write Read/Write

Events of TextBox

Name
Enter GotFocus Leave Validating Validated LostFocus KeyDown KeyPress

Description
These six events occur in the order they are listed here. They are known as "Focus Events" and are fired whenever a controls focus changes, with two exceptions. Validating and Validated are only fired if the control that receives focus has the CausesValidation property set to true. The reason why it's the receiving control that fires the event is that there are times where you do not want to validate the control, even if focus changes. An example of this is if the user clicks a Help button. These three events are known as "Key Events". They allow you to monitor and change what is entered into your controls.

KeyDown and KeyUp receive the key code corresponding to the key that was pressed. This allows you to determine if special keys such as Shift or Control and F1 were pressed. KeyUp KeyPress, on the otherhand, receives the character corresponding to a keyboard key. This means that the value for the letter "a" is not the same as the letter "A". It is useful if you want to exclude a range of characters, for example, only allowing numeric values to be entered. Occurs whenever the text in the textbox is changed, no matter what the change.

Change

TextBox Test

First Design a form on choosing New Project of Windows Application. and then set the properties of label, button and forms like shown in above picture. Adding the events Code for Ok Button Click Private Sub ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ok.Click If nametxt.Text = "" OrElse TextBox2.Text = "" OrElse TextBox3.Text =

""

OrElse TextBox4.Text = "" Then MessageBox.Show("Please fill all Information", "Alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) Else Dim output As String 'Concatenate the text values of the four TextBoxes output = "Name: " & Convert.ToString(Me.nametxt.Text) & vbCr & output += "Address: " & Convert.ToString(Me.TextBox2.Text) & vbCr output += "Occupation: " & Convert.ToString(Me.TextBox3.Text) &

vbLf & vbLf vbCr & vbLf

output += "Age: " & Convert.ToString(Me.TextBox4.Text) ' Insert the new text Me.TextBox5.Text = output End If End Sub

Code for Help Button Click Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim output As String output = "Name = Enter Your name" & vbCr & vbLf output += "Address = Enter Your address" & vbCr & vbLf output += "Occupation = Enter Occupation" & vbCr & vbLf output += "Age = Enter Your age" ' Insert the new text Me.TextBox5.Text = output End Sub Adding Events on TextBox Event on TextBox Leave Event Private Sub nametxt_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nametxt.Leave If nametxt.Text = "" Then nametxt.BackColor = Color.Red End If End Sub Event on TextBox Keypress Event

Private Sub nametxt_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles nametxt.KeyPress If nametxt.BackColor = Color.Red Then nametxt.BackColor = Color.Snow End If End Sub

Radio Button

Radio buttons themselves as a label with a dot to the left of it, which can be either selected or not. You should use the radio buttons when you want to give the user a choice between several mutually exclusive options. for Example, if you want to ask for the gender of the user. To group radiobuttons together so that they create one logical unit you must use a GroupBox control. By first placing a group box on a form, and then placing the RadioButton controls you need within the borders of the group box, the RadioButton controls will know to change their state to reflect that only one within the group box can be selected. If you do not place them within a group box, only one RadioButton on the form can be selected at any given time.

CheckBox Controls
A CheckBox traditionally displays itself as a label with a small box with a checkmark to the left of it. You should use the check box when you want to allow the user to choose one or more options. An example could be a questionnaire asking which operating systems the user has tried (for example, Windows 95, Windows 98, Linux, Max OS X, and so on.)

RadioButton Properties Name Availability Description


A RadioButton can be displayed either as a label with a circular check to the left, middle or right of it, or as a standard button. When it is displayed as a button, the control will appear pressed when selected and 3D otherwise. When this property is true, a check mark is displayed when the user clicks the radio button. When it is false, the check mark is not displayed by default. By using this property, you can change the alignment of the radio button. It can be left, middle, and right. Indicates the status of the control. It is true if the control has a check mark, and false otherwise.

Appearance

Read/Write

AutoCheck

Read/Write

CheckAlign

Read/Write

Checked

Read/Write

RadioButton Events

Name

Description

This event is sent when the check of the RadioButton changes. If there is more than one RadioButton control on CheckChanged the form or within a group box, this event will be sent twice, first to the control, which was checked and now becomes unchecked, then to the control which becomes checked. This event is sent every time the RadioButton is clicked. This is not the same as the change event, because clicking a RadioButton twice or more times in succession only changes Click the checked property once ? and only if it wasn't checked already.

CheckBox Properties Name Availability Description


Unlike the RadioButton, a CheckBox can have three states: Checked, Indeterminate, and Unchecked. When the state of the check box is Indeterminate, the control check next to the label is usually grayed, indicating that the current value of the check is not valid or has no meaning under the current circumstances. An example of this state can be seen if you select several files in the Windows Explorer and look at their properties. If some files are ReadOnly and others are not, the ReadOnly checkbox will be checked, but grayed indeterminate. When this property is false, the user will not be able to change the CheckBox' state to Indeterminate. You can, however, still change the state of the check box to Indeterminate from code.

CheckState Read/Write

ThreeState Read/Write

CheckBox Events Name Description

Occurs whenever the Checked property of the check box changes. Note that in a CheckBox where the ThreeState property is true, it is possible to click the CheckedChanged check box without changing the Checked property. This happens when the check box changes from checked to indeterminate state. Occurs whenever the CheckedState property changes. As Checked and Unchecked are both possible values of the CheckedState property, this event will be sent CheckedStateChanged whenever the Checked property changes. In addition to that, it will also be sent when the state changes from Checked to Indeterminate.

Example: In following image i have created a window form for saving information of student like personal info and subjects of his/her. For this you have to drag and drop 4 textboxes, 2 radiobuttons, 5 labels and 3 buttons. Change all controls properties like in picture.

In figure 2 if user direct click on ok button then he/she will get massage for alert to fill all information. In Figure 3 if user fill personal information and then click on Ok button then he/she will get alert message for choosing gender. And in figure 4 if user not choose subject and click on ok button then he will get another alert message for choosing subject. To making all these validation you have to write following code on Ok button Click. Code For Ok Button Click: Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click If textBox1.Text = "" OrElse textBox2.Text = "" OrElse textBox4.Text = "" Then MessageBox.Show("Please fill all personal information", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) ElseIf radioButton1.Checked = False AndAlso radioButton2.Checked = False Then MessageBox.Show("Please select Gender", "Warning", MessageBoxButtons.OKCancel,

MessageBoxIcon.Warning) ElseIf checkedListBox1.Text = "" Then MessageBox.Show("Please select Subjects", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) Else If radioButton1.Checked Then ' Concatenate the text values of the four TextBoxes output = "Name: " & Convert.ToString(Me.textBox1.Text) & vbCr & vbLf output += "Address: " & Convert.ToString(Me.textBox2.Text) & vbCr & vbLf output += "Course: " & Convert.ToString(Me.textBox4.Text) & vbCr & vbLf output += "Sex: " & Convert.ToString(Me.radioButton1.Text) & vbCr & vbLf output += "Subject:" For Each [sub] As String In checkedListBox1.CheckedItems output += " " & [sub] Next End If If radioButton2.Checked Then ' Concatenate the text values of the four TextBoxes output = "Name: " & Convert.ToString(Me.textBox1.Text) & vbCr & vbLf output += "Address: " & Convert.ToString(Me.textBox2.Text) & vbCr & vbLf output += "Course: " & Convert.ToString(Me.textBox4.Text) & vbCr & vbLf output += "Sex: " & Convert.ToString(Me.radioButton2.Text) & vbCr & vbLf output += "Subject:" For Each [sub] As String In checkedListBox1.CheckedItems output += " " & [sub] Next End If Me.textBox3.Text = output End If End Sub Now if you to give condition for user that he should must choose at least three subjects then you can add code for this on Checklistbox Leave Event. Like following code. Code for Leave Event on Checklist Box. Private Sub CheckedListBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckedListBox1.Leave Dim count As Integer =

CheckedListBox1.CheckedItems.Count If True Then If count <= 3 Then MessageBox.Show("Your minimum choice is Three subject") End If End If End Sub

Final output will show like in below figure

GroupBox Control
Windows Forms GroupBox controls are used to provide a most important facility for grouping other controls. Typically, you use group boxes to subdivide a form by function. For example, you may have an order form that specifies mailing options such as which overnight carrier to use. Grouping all options in a group box gives the user a logical visual cue. The GroupBox control is similar to the Panel control; however, only the GroupBox control displays a caption, and only the Panel control can have scroll bars.

Group Box Properties

Group Box Event:

Rich TextBox Control


Like the normal TextBox, the RichTextBox control is derived from TextBoxBase. Because of this, it shares a number of features with the TextBox, but is much more diverse. Where a TextBox is commonly used with the purpose of obtaining short text strings from the user, the RichTextBox is used to display and enter formatted text (for example bold, underline, and italic). It does so using a standard for formatted text called Rich Text Format or RTF. RichTextBox Properties

Name

Availability

Description

CanRedo

Read only

This property is true if something has been undone, that can be reapplied, otherwise false. This property is true if it is possible to perform an undo action on the RichTextBox, otherwise it is false. This property holds the name of an action that be used to redo something that has been undone in the RichTextBox. Set this property to true to make the control detect URLs and format them (underline as in a browser). This corresponds to the Text property, except that this holds the text in RTF. Use this property to get or set the selected text in the control, in RTF. If you copy this text to another application, for example, MS Word, it will retain all formatting. Like SelectedRtf you can use this property to get or set the selected text. Unlike the RTF version of the property however, all formatting is lost. This represents the alignment of the selected text. It can be Center, Left, or Right. Use this property to find out if the selection is formatted with a bullet in front of it, or use it to insert or remove bullets. Use this property to specify the number of pixels a bullet should be indented. Allow you to change the color of the text in the selection. Allow you to change to font of the text in the selection. Using this property, you either set or retrieve the length of a selection. This property holds information about the selection. It will tell you if one or more OLE objects are selected or if only text is selected. If you set this property to true, a margin will be shown at the left of the RichTextBox. This will make it easier for the user to select text. Gets the name of the action that will be used if the user chooses to undo something. You can specify that certain parts of the text should not be changed by setting this property to true.

CanUndo

Read only

RedoActionName

Read only

DetectUrls Rtf

Read/Write Read/Write

SelectedRtf

Read/Write

SelectedText SelectionAlignment SelectionBullet BulletIndent SelectionColor SelectionFont SelectionLength SelectionType

Read/Write Read/Write Read/Write Read/Write Read/Write Read/Write Read/Write Read only

ShowSelectionMargin Read/Write UndoActionName SelectionProtected Read only Read/Write

RichTextBox Events

Name
LinkedClick

Description

This event is sent when a user clicks on a link within the text. This event is sent when a user attempts to modify Protected text that has been marked as protected. This event is sent when the selection changes. If SelectionChanged for some reason you don't want the user to change the selection, you can prevent the change here. Example of Rich TextBox: To implement rich textbox create new application and design form like below image, and change properties according to your choice.

In following image i am making selected text bold on clicking the bold Button. Coding for bold button is given below.

Code for Bold Button Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim oldFont As Font Dim newFont As Font ' Get the font that is being used in the selected text oldFont = Me.richTextBox1.SelectionFont ' If the font is using bold style now, we should remove the ' Formatting If oldFont.Bold Then newFont = New Font(oldFont, oldFont.Style And Not FontStyle.Bold) Else newFont = New Font(oldFont, oldFont.Style Or FontStyle.Bold) End If ' Insert the new font and return focus to the RichTextBox Me.richTextBox1.SelectionFont = newFont Me.richTextBox1.Focus() End Sub

In following image i am making selected text Italic on clicking the italic Button. Coding for italic button is given below.

Code for Italic Button Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim oldFont As Font Dim newFont As Font ' Get the font that is being used in the selected text oldFont = Me.richTextBox1.SelectionFont ' If the font is using Italic style now, we should remove it If oldFont.Italic Then newFont = New Font(oldFont, oldFont.Style And Not FontStyle.Italic) Else newFont = New Font(oldFont, oldFont.Style Or FontStyle.Italic) End If

' Insert the new font Me.richTextBox1.SelectionFont = newFont Me.richTextBox1.Focus() End Sub

In following image i am making selected text Underline on clicking the Underline Button. Coding for Underline Button is given below.

Coding for Underline Button Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim oldFont As Font Dim newFont As Font ' Get the font that is being used in the selected text oldFont = Me.richTextBox1.SelectionFont ' If the font is using Italic style now, we should remove it If oldFont.Italic Then

newFont = New Font(oldFont, oldFont.Style And Not FontStyle.Italic) Else newFont = New Font(oldFont, oldFont.Style Or FontStyle.Italic) End If ' Insert the new font Me.richTextBox1.SelectionFont = newFont Me.richTextBox1.Focus() End Sub In following image i am making selected text Center on clicking the Center Button. Coding for Center Button is given below.

Coding for Center Button Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click If Me.richTextBox1.SelectionAlignment = HorizontalAlignment.Center Then Me.richTextBox1.SelectionAlignment = HorizontalAlignment.Left Else

Me.richTextBox1.SelectionAlignment = HorizontalAlignment.Center End If Me.richTextBox1.Focus() End Sub In following image i am making selected text size large and small by putting the value in size textbox. Coding for this is given below.

Coding for Size Change for this you have to write following code on textbox validating event. Private Sub txtSize_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtSize.Validating Dim txt As TextBox = DirectCast(sender, TextBox) ApplyTextSize(txt.Text) Me.richTextBox1.Focus() End Sub And then you have to write keypress event on textbox event.

Private Sub txtSize_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSize.KeyPress If (e.KeyChar < 48 OrElse e.KeyChar > 57) AndAlso e.KeyChar <> 8 AndAlso e.KeyChar <> 13 Then e.Handled = True ElseIf e.KeyChar = 8 Then MessageBox.Show("Please input valid size") ElseIf e.KeyChar = 13 Then ' Apply size if the user hits enter Dim txt As TextBox = DirectCast(sender, TextBox) If txt.Text.Length > 0 Then ApplyTextSize(txt.Text) End If e.Handled = True Me.richTextBox1.Focus() End If End Sub and then make a method for applytextsize method Private Sub ApplyTextSize(textSize As String) ' Convert the text to a float because we'll be needing a float shortly Dim newSize As Single = Convert.ToSingle(textSize) Dim currentFontFamily As FontFamily Dim newFont As Font ' Create a new font of the same family but with the new size currentFontFamily = Me.richTextBox1.SelectionFont.FontFamily newFont = New Font(currentFontFamily, newSize) ' Set the font of the selected text to the new font Me.richTextBox1.SelectionFont = newFont End Sub

ListBox Controls
These controls are used to show a list of strings from which one or more can be selected at a time. Just like check boxes and radio buttons, the list box provides a means of asking the user to make one or more selections. You should use a list box when at design time you don't know the actual number of values the user can choose from (an example could be a list of co-workers). Even if you know all the possible values at design time, you should consider using a list box if there are a great number of values.

Properties of Listbox Name


SelectedIndex

Availability
Read/Write

Description
This value indicates the zero-based index of the selected item in the list box. If the list box can contain multiple selections at the same time, this property holds the index of the first item in the selected list. In a list box with multiple columns, this property specifies the width of the columns. The Items collection contains all of the items in the list box. You use the properties of this collection to add and remove items. A list box can have more than one column. Use this property the get or set the number of columns in the list box. This property is a collection, which holds all of the zero-based indices of the selected items in the list box. In a list box where only one item can be selected, this property contains the selected item if any. In a list box where more than one selection can be made, it will contain the first of the selected items. This property is a collection, which contains all of the items currently selected. You can choose between four different modes of selection in a list box: q None: No items can be selected.

ColumnWidth Items

Read/Write Read-only

MultiColumn

Read/Write

SelectedIndices

Read-only

SelectedItem

Read/Write

SelectedItems SelectionMode

Read-only Read/Write

q One: Only one item can be selected at any time. q MultiSimple: Multiple items can be selected. q MultiExtended: Multiple items can be selected and the user can use the Ctrl, Shift and arrows keys to make selections. Setting this property to true will cause the ListBox to sort the items it contains alphabetically. We've seen Text properties on a number of controls, but this one works very differently than any we've seen so far. If you set the Text property of the list box control, it searches for an item that matches the text, and selects it. If you get the Text property, the value returned is the first selected item in the list. This property cannot be used if the SelectionMode is None. (CheckedListBox only) This property is a collection, which contains all indexes in the CheckedListBox that is a checked or indeterminate state. (CheckedListBox only) This is a collection of all the items in a CheckedListBox that are in a checked or indeterminate state. (CheckedListBox only) If this property is true, an item will change its state whenever the user clicks it. (CheckedListBox only) You can choose between Checkboxes that are flat or normal by setting this property.

Sorted

Read/Write

Text

Read/Write

CheckedIndicies

Read-only

CheckedItems

Read-only

CheckOnClick

Read/Write

ThreeDCheckBoxes Read/Write

ListBox Methods

Name
ClearSelected FindString FindStringExact GetSelected SetSelected ToString GetItemChecked

Description
Clears all selections in the ListBox, Finds the first string in the ListBox beginning with a string you specify for example FindString("a") will find the first string in the ListBox beginning with 'a' Like FindString but the entire string must be matched Returns a value that indicates whether an item is selected Sets or clears the selection of an item Returns the currently selected item (CheckedListBox only) Returns a value indicating if an item

is checked or not (CheckedListBox only) Returns a value indicating the check GetItemCheckState state of an item (CheckedListBox only) Sets the item specified to achecked SetItemChecked state. SetItemCheckState (CheckedListBox only) Sets the check state of an item ListBox Events

Name

Description

(CheckedListBox only) Occurs when the check state of ItemCheck one of the list items changes SelectedIndexChanged Occurs when the index of the selected item changes Sample Example for ListBox control In following image i have taken 2 ListBox controls and 4 buttons and add items in ListBox one with collection property of this.and change property according to your choice.

My purpose of taking two ListBox is for moving items from listbox1 to ListBox 2 by button click ad show below with single selection and multi selection if user click on button without selecting item from listbox1 then he/she will get alert message for choosing items from ListBox. Code for this is given below

Write following code on Single selection Button by double click on button. Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If listBox1.SelectedIndex >= 0 Then Dim selectitem As String = listBox1.SelectedItem.ToString() listBox2.Items.Add(selectitem) listBox1.Items.Remove(selectitem)

Else

MessageBox.Show("Please Choose Item to move", "Warning") End If End Sub

Code for moving all items from one ListBox to another. Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click For Each item As String In listBox1.Items listBox2.Items.Add(item) Next listBox1.Items.Clear() End Sub You will get output as follows

Similarly you can write for moving items from listbox2 to listbox1.

ComboBox Controls
The ComboBox control is used to save space on a dialog because the only part of the combo box that is permanently visible are the text box and button parts of the control. When the user clicks the arrow button to the right of the text box, a list box unfolds in which the user can make a selection. As soon as he or she does so, the list box disappears and the display returns to normal. As the name implies, a combo box combines a number of controls, to be specific the TextBox, Button, and ListBox controls. Unlike the ListBox, it is never possible to select more than one item in the list of items contained in a ComboBox and it is optionally possible to type new entries in the list in the TextBox part of the ComboBox.

ComboBox Properties

Name

Availability

Description
A combo box can be displayed with three different styles: q DropDown: The user can edit the text box part of the control, and must click the arrow button to display the list part of the control. q Simple: Same as DropDown, except that the list part of the control is always visible, much like a normal ListBox. q DropDownList: The user cannot edit the text box part of the control, and must click the arrow button to display the list part of the control. Indicates whether the list part of the control is dropped down or not. If you set this property to true, the list will unfold. This property is a collection, which contains all the items in the list contained in the combo box. By setting this property to anything other than zero, you control the maximum number of characters it is possible to enter into the text box part of the control. Indicates the index of the currently selected item in the list. Indicates the item that is currently selected in the list.

DropDownStyle Read/Write

DroppedDown

Read/Write

Items

Read-only

MaxLength

Read/Write

SelectedIndex Read/Write SelectedItem Read/Write

SelectedText SelectionStart

Read/Write Read/Write

SelectionLengthRead/Write Sorted Read/Write

Text

Read/Write

Represents the text that is selected in the text box part of the control. In the text box part of the control, this property represents the index of the first character that is selected. The length of the text selected in the text box part of the control. Set this property to true to make the control sort the items in the list portion alphabetically. If you set this property to null, any selection in the list portion of the control is removed. If you set it to a value, which exists in the list part of the control, that value is selected. If the value doesn't exist in the list, the text is simply shown in the text portion.

ComboBox Events Description Occurs when the list portion of the control is dropped DropDown down. Occurs when the selection in the list portion of the SelectedIndexChanged control changed. These events occur when a key is pressed while the text KeyDown, KeyPress, portion of the control has focus. Please refer to the KeyUp descriptions of the events in the text box section earlier in this chapter. TextChanged Occurs when the Text property changes ComboBox Text Example In following image i have designed a window form for saving the address of user. Make design of your application in following image manner and change properties according to you. Name

In following figure for selecting country i have used ComboBox for selecting country and after that he/she will get the name of corresponding state name of that country he/she selected. Code for Combobox1 to add the items in Combobox2. Write following code on Combobox1 selected index change Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged comboBox2.Items.Clear() comboBox2.Enabled = True If ComboBox1.SelectedItem.ToString() = "India" Then comboBox2.Items.Add("NewDelhi") comboBox2.Items.Add("Chennai") comboBox2.Items.Add("Banglore") comboBox2.Items.Add("Mumbai") ElseIf ComboBox1.SelectedItem.ToString() = "Australia" Then comboBox2.Items.Add("Sydney") comboBox2.Items.Add("Johnsberg") comboBox2.Items.Add("Perth") comboBox2.Items.Add("Melborn") ElseIf ComboBox1.SelectedItem.ToString() = "United States" Then comboBox2.Items.Add("NewYork") comboBox2.Items.Add("Los Ageles") comboBox2.Items.Add("California") comboBox2.Items.Add("LosBegas") End If End Sub

After that choosing State name he/she will get the location in ComboBox 3. Like in following figure.

Code for ComboBox2 is given below write that code on Combobox2 Selected Index Changed Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles ComboBox2.SelectedIndexChanged comboBox3.Items.Clear() comboBox3.Enabled = True If ComboBox2.SelectedItem.ToString() = "NewDelhi" Then comboBox3.Items.Add("East Delhi") comboBox3.Items.Add("West Delhi") comboBox3.Items.Add("North Delhi") comboBox3.Items.Add("South Delhi") ElseIf ComboBox2.SelectedItem.ToString() = "Chennai" Then comboBox3.Items.Add("Chennai") ElseIf ComboBox2.SelectedItem.ToString() = "Mumbai"

Then

comboBox3.Items.Add("Mumbai") comboBox3.Items.Add("Navi Mumbai") ElseIf ComboBox2.SelectedItem.ToString() = "Banglore" Then comboBox3.Items.Add("Banglore") ElseIf ComboBox2.SelectedItem.ToString() = "Johnsberg" Then comboBox3.Items.Add("Johnsberg") ElseIf ComboBox2.SelectedItem.ToString() = "Sydney" comboBox3.Items.Add("Sydney") ElseIf ComboBox2.SelectedItem.ToString() = "Perth" Then comboBox3.Items.Add("Perth") End If End Sub

Then

Code for Save Button Click Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim output As String output = "Name: " & Convert.ToString(Me.textBox1.Text) & vbCr & vbLf output += "Address : " & Convert.ToString(Me.textBox2.Text) & vbCr & vbLf output += " " & Convert.ToString(Me.textBox3.Text) & vbCr & vbLf output += " " & Convert.ToString(Me.comboBox3.Text) & vbCr & vbLf output += " " & Convert.ToString(Me.ComboBox2.Text) & vbCr & vbLf output += "Country: " & Convert.ToString(Me.ComboBox1.Text) & vbCr & vbLf textBox4.Text = output End Sub Final you will get output Like this.

StatusBar Control
A status bar is commonly used to provide hints for the selected item or information about an action currently being performed on a dialog. Normally, the StatusBar is placed at the bottom of the screen, as it is in MS Office applications and Paint, but it can be located anywhere you like. StatusBar Properties

Name

Availability

Description
It is possible to assign an image to the status bar that will be drawn in the background. This is the collection of panels in the status bar. Use this collection to add and remove panels. If you want to display panels, this property must be set to true. When you are not using panels this property holds the text that is displayed in the status bar.

BackgroundImage Read/Write Panels ShowPanels Text Read-only Read/Write Read/Write

StatusBar Events Name


DrawItem PanelClick

Description
Occurs when a panel that has the OwnerDraw style set needs to be redrawn. You must subscribe to this event if you want to draw the contents of a panel yourself. Occurs when a panels is clicked.

The StatusBarPanel Class This class contains all the information about the individual panels in the Panels collection. The information that can be set ranges from simple text and alignment of text to icons to be displayed and the style of the panel. Example For StatusBar To understanding StatusBar control drag and drop status strip and make text blank and add 2toolstatuslabel and 1 toolstatusprogressbar. And drag 1textbox and 1 button,1timer control and change property according to your choice.

Code for button click on go button


Private Sub Button1_Click_1(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles Button1.Click toolStripProgressBar1.Visible = True toolStripStatusLabel2.Text = "" timer1.Enabled = True webBrowser1.Navigate(textBox1.Text) toolStripStatusLabel1.Text = textBox1.Text End Sub

On clicking button progress bar will show on status strip control until webpage will not open. when web page is loaded progress bar will not be display and label text will be web address and done that means page has been loaded as shown below

Code for timer Control Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick toolStripProgressBar1.Value = toolStripProgressBar1.Value + 10 If toolStripProgressBar1.Value = toolStripProgressBar1.Maximum Then toolStripProgressBar1.Value = 0 toolStripProgressBar1.Visible = False Timer1.Enabled = False toolStripStatusLabel2.Text = "Done" End If End Sub

Write following code on document complete event of WebbrowserControl so that progressbar stoped Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted toolStripProgressBar1.Visible = False End Sub

Tabcontrol Control
The TabControl provides an easy way of organizing a dialog into logical parts that can be accessed through tabs located at the top of the control. A TabControl contains TabPages that essentially work in a similar way to a GroupBox control, though it is somewhat more complex:

TabControl Properties

Name
Alignment Appearance

Availability
Read/Write Read/Write

Description
Controls where on the tab control the tabs are displayed. The default is at the top. Controls how the tabs are displayed. The tabs can be displayed as normal buttons or with flat style. If this property is set to true the appearance of the tabs on the control change as, the mouse pointer passes over them. If this property is set to true, it is possible to have several rows of tabs. Returns the number of rows of tabs that is currently displayed. Returns or sets the index of the selected tab. Returns the total number of tabs. This is the collection of TabPages in the control. Use this collection to add and remove TabPages.

HotTrack Multiline RowCount

Read/Write Read/Write Read-only

SelectedIndexRead/Write TabCount Read-only TabPages Read-only

Working with TabControl Drag and drop a TabControl and add pages as show in below picture.

Now change the text property of the TabControl tab page as shown in below picture.

Design according to your choice or shown in below image.

Code for picking date- for this add a month calendar and make visibility false and true its visibility on PickDate button click. Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click monthCalendar1.Visible = True End Sub

Private Sub MonthCalendar1_DateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DateRangeEventArgs) Handles MonthCalendar1.DateChanged textBox3.Text = DateTime.Now.ToLongDateString() MonthCalendar1.Visible = False End Sub

On clicking next button you can move on next TabIndex code for this is given belowPrivate Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked If textBox1.Text = "" OrElse textBox2.Text = "" OrElse textBox3.Text = "" Then MessageBox.Show("Please fill your personal information") Else Me.tabControl1.SelectedIndex = 1 End If End Sub

Code for previous button Click Private Sub LinkLabel3_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel3.LinkClicked Me.tabControl1.SelectedIndex = 0 End Sub

NotifyIcon Control
Display an icon on notification area with corresponding to the application is running. Like shown in below example.

Properties of NotifyIcon

Events of Notify Icon

Code for mouse double click event on NotifyIcon Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick If Me.WindowState = FormWindowState.Minimized Then Me.Show() Me.WindowState = FormWindowState.Normal End If ' Activate the form. Me.Activate() Me.Focus() End Sub

On double-clicking Icon to tab control application you get your application as on desktop.

Masked Textbox
Sets the string governing the input allowed for this control. Masked TextBox is intelligent user control enhances the function of the TextBox control, which can mask the Date, IP Address, SSN, Phone numbers, digits, decimal and checks the validation, and automatically set the delimiter location. The property Masked is set to None by default and the control works like a normal TextBox control. If setting the property to Date Only, the control is masked to Date format. Like shown in below Image:

Code for Ok Button Click Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click label2.Text = label2.Text + maskedTextBox1.Text End Sub

Window Media Player


You will not find the window media player control on toolbox list, so you have to add this control on rightclick on tool box and select option choose item as shown in below picture.

After this you will get another window for choosing toolbox item go to COM component panel and check window media player item and then click ok button. This control will add on your Visual Studio Framework toolbox list.

Now you can drag and drop window media player control from toolbox list.

Code for playing a song on window media player. Private Sub Form1_Load(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles MyBase.Load axWindowsMediaPlayer1.URL = "D:\Documents and Settings\R4R\ My Documents\Downloads\aakrosh02(www.songs.pk).mp3" End Sub

Dialog Controls

Code for New Button


Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click If richTextBox1.Modified Then Dim result As DialogResult = MessageBox.Show("Do you wish to Save changes?", "Save Changes",

MessageBoxButtons.YesNoCancel) If result = DialogResult.Yes Then saveToolStripMenuItem_Click(sender, e) ElseIf result = DialogResult.No Then richTextBox1.Text = "" End If If result = DialogResult.Cancel Then End If End If End Sub

Code For Open Button


Private Sub OpenToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem1.Click If OpenFileDialog1.ShowDialog() = DialogResult.OK Then richTextBox1.LoadFile(OpenFileDialog1.FileN ame, RichTextBoxStreamType.PlainText) SaveFileDialog1.FileName = OpenFileDialog1.FileName End If End Sub

Code for Save Button


Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click If SaveFileDialog1.FileName <> "" Then richTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.PlainText) Else saveAsToolStripMenuItem_Click(sender, e) End If End Sub

Code for Save As Button


Private Sub SaveToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem1.Click If SaveFileDialog1.ShowDialog() = DialogResult.OK Then richTextBox1.SaveFile(SaveFileDialog1.Fil eName, RichTextBoxStreamType.PlainText)

End If End Sub

Code for Exit Button


Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click If richTextBox1.Modified Then Dim result As DialogResult = MessageBox.Show("Do you wish to Save changes?", "Save Changes", MessageBoxButtons.YesNoCancel) If result = DialogResult.Yes Then SaveToolStripMenuItem_Click(sender, e) ElseIf result = DialogResult.Cancel Then End If End If Me.Close() End Sub

Code for Form Closing


Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing If richTextBox1.Modified Then Dim result As DialogResult = MessageBox.Show("Do you wish to Save changes?", "Save Changes", MessageBoxButtons.YesNoCancel) If result = DialogResult.Yes Then SaveToolStripMenuItem_Click(sender, e) ElseIf result = DialogResult.Cancel Then e.Cancel = True End If End If End Sub

Printing Controls
These controls are used to take printing of documents whether in form of print screen or as printing in the content form . In following figure i tried to describe about these controls how you will use in your window application. For explaining this i had taken the previous example of dialog control, so lets proceed with printing controls.

Code for Print Preview- For performing this action first add namespace
Imports System.Drawing.Printing Private PrintDoc1 As New PrintDocument() Private PrintPreviewDialog1 As New PrintPreviewDialog() Private Sub printToolStripMenuItem_Click(sender As Object, e As EventArgs) PrintPreviewDialog1.Document = PrintDoc1 PrintDoc1.OriginAtMargins = True 'To set or Get the Position of a Graphic Object PrintDoc1.PrintPage += PDoc_PrintPage PrintPreviewDialog1.ShowDialog() End Sub

Create Method Private Sub PDoc_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PDoc.PrintPage Dim bmp As New Bitmap(Me.Width, Me.Height) Me.DrawToBitmap(bmp, Me.ClientRectangle) Me.DrawToBitmap(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height)) 'Takes the Snap of the Exact WindowForm size as Bitmap image e.Graphics.DrawImage(bmp, 0, 0) End Sub

Code for taking Print Private Sub PrintToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

PrintToolStripMenuItem.Click PrintDoc1.Print() End Sub

Data Controls
For understanding data controls design form like shown in below picture and take datagrid view control from toolbox. And add new database from solution explorer by choosing new item. Add namespace Imports System.Data.SqlClient

Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename= D:\Documents and Settings\R4R\My Documents\Visual Studio 2008\Projects\

WindowsFormsApplication14\WindowsFormsApplication14\r4r.mdf;Integrated Security=True;User Instance=True")

Now inserted record in database by clicking on insert button. Code for this is given belowCode for inserting Data in Database Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim com As New SqlCommand((((("insert into emp_detail values('" + textBox1.Text & "','") + textBox2.Text & "','") + textBox3.Text & "','") + textBox4.Text & "','") + textBox5.Text & "')", con) con.Open() com.ExecuteNonQuery() con.Close() End Sub

Code for viewing the total record in DataGridview by clicking the view button Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click Dim com2 As New SqlCommand("select * from emp_detail", con) Dim da As New SqlDataAdapter(com2) Dim ds As New DataSet() con.Open() da.Fill(ds, "emp_detail") con.Close() dataGridView1.DataSource = ds.Tables(0) End Sub

Code for Updating the record from dataGrid View. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click For Each row As DataGridViewRow In dataGridView1.SelectedRows If row.Index <> dataGridView1.Rows.Count Then id = dataGridView1.SelectedRows(0).Cells(0).Value.ToString() Name = dataGridView1.SelectedRows(0).Cells(1).Value.ToString() address = dataGridView1.SelectedRows(0).Cells(2).Value.ToString() sal = dataGridView1.SelectedRows(0).Cells(3).Value.ToString() cont = dataGridView1.SelectedRows(0).Cells(4).Value.ToString() dataGridView1.Rows.RemoveAt(row.Index) End If Next Dim com3 As New SqlCommand("update emp_detail set emp_name='" & Name & "',emp_address='" & address & "',emp_sal='" & sal & "',emp_cont='" & cont & "' where emp_id ='" & id & "'", con) con.Open() com3.ExecuteNonQuery()

con.Close() End Sub

Code for Deleting the recording from Datagridview control Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click For Each row As DataGridViewRow In dataGridView1.SelectedRows If row.Index <> dataGridView1.Rows.Count Then id = dataGridView1.SelectedRows(0).Cells(0).Value.ToString() dataGridView1.Rows.RemoveAt(row.Index) End If Next Dim com3 As New SqlCommand("delete from emp_detail where emp_id ='" & id & "'", con) con.Open() com3.ExecuteNonQuery() con.Close() End Sub

Error Provider Control


This control provides a user interface that indicates to user that a control on a form has error associated with it. In other had it works as validation upon the controls to handle the error causes by inputting wrong by user. Drag this control as shown in below picture -

Adding error provider control on textbox for blank not allowWrite this code on textbox validating event- Output will shown in below picture if user leave name blank. Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating ValidateName() End Sub Private Function ValidateName() As Boolean Dim bStatus As Boolean = True If textBox1.Text = "" Then errorProvider1.SetError(textBox1, "Please enter your Name") bStatus = False

errorProvider1.SetError(textBox1, "") End If Return bStatus End Function

Else

Validating for age. For validating age i have covered three conditions for validate 1-If user leave this blank. 2-If entered age is less than 18. 3-If user input character value in place of numeric. Write this code on Textbox2 validating Event Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged ValidateAge() End Sub Private Function ValidateAge() As Boolean Dim bStatus As Boolean = True If textBox2.Text = "" Then errorProvider1.SetError(textBox2, "Please enter your Age") bStatus = False Else errorProvider1.SetError(textBox2, "") Try Dim temp As Integer = Integer.Parse(textBox2.Text) errorProvider1.SetError(textBox2, "") If temp < 18 Then

errorProvider1.SetError(textBox2, "You must be atleast 18 years old to setup a test") Else bStatus = False

errorProvider1.SetError(textBox2, "") End If Catch errorProvider1.SetError(textBox2, "Please enter your age as a number") bStatus = False End Try End If Return bStatus End Function Output of this error provider is shown below

Using error provider control on DatetimePicker Control If user select weekend day for test then he will get error message- Like shown in below picture Private Sub DateTimePicker1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles DateTimePicker1.Validating ValidateTestDate() End Sub Private Function ValidateTestDate() As Boolean Dim bStatus As Boolean = True If (dateTimePicker1.Value.DayOfWeek = DayOfWeek.Sunday) OrElse (dateTimePicker1.Value.DayOfWeek = DayOfWeek.Saturday) Then errorProvider1.SetError(dateTimePicker1, "Appointment cannot be scheduled in the weekend. Please select a weekday") bStatus = False Else errorProvider1.SetError(dateTimePicker1, "") End If Return bStatus End Function Write above code on DatetimePicker Validating Event.

Help Provider
This control is used to provide pop-up and online help to user on pressing F1 key. Drag and Drop Help provider as show in below picture.

Code for using Help Provider- Write following code on Page load Event. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load helpProvider1.SetHelpString(textBox1, "Enter your Name ") helpProvider1.SetHelpString(textBox2, "Enter your Age") helpProvider1.SetHelpString(DateTimePicker1, "Pich date for giving test") End Sub You will get output as shown below picture on pressing F1 key.

Flow Layout Panel


The FlowLayoutPanel control is a container control where child controls are added, then dynamically repositioned to flow in a particular direction. The FlowLayoutPanel automatically positions all child controls in the direction indicated by the value of the FlowDirection property. Useful properties AutoScroll - This property when set to true, allows scroll bars to be displayed. BackColor - The background color of the Panel is defaulted to System.Drawing.SystemColors.Control, but this can be set to any color you like. BackgroundImage - Instead of a single color, an image can be displayed as the background. BorderStyle - This property determines if the panel is outlined with no visible border (None), a plain line (FixedSingle), or a shadowed line (Fixed3D). Controls - Gets the collection of controls contained within the control. Enabled - If this property is set to false, the controls contained within the Panel will also be disabled. FlowDirection - Gets or sets a value indicating the flow direction of the FlowLayoutPanel control. This property takes a value from the FlowDirection enumeration, the default value is LeftToRight: BottomUp - Elements flow from the bottom of the design surface to the top. LeftToRight - Elements flow from the left edge of the design surface to the right. RightToLeft - Elements flow from the right edge of the design surface to the left.

TopDown - Elements flow from the top of the design surface to the bottom. TabIndex - Gets or sets the tab order of the control within its container. TabStop - Gets or sets a value indicating whether the user can give the focus to this control using the TAB key. WrapContents - Gets or sets a value indicating whether the FlowLayoutPanel control should wrap its contents or let the contents be clipped. Useful methods GetFlowBreak - Returns a value that represents the flow-break setting of the FlowLayoutPanel control. SetFlowBreak - Sets the value that represents the flow-break setting of the FlowLayoutPanel control. Example- First drag and drop FloyLayout Panel and add controls like- label->textbox>label->textbox->button. You will see that your controls are adding from left to right because by default Flawlayout Panel Property i.e.. FlowDirection is left to right. So for understanding this i have taken one checkbox to make wrapping controls in Flow layout panel. By default it is false in Flow layout panel.

Code for check box event for wrapping control Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged flowLayoutPanel1.WrapContents = True

End Sub

Table Layout Panel


The TableLayoutPanel control is a container control where child controls are added within a table structure. Each cell in the table contains a single control, unless a container such as a Panel is added first. Useful properties CellBorderStyle - This property determines if the cell is outlined with a border or not. A

value from the TableLayoutPanelCellBorderStyle enumeration is required, the default value is None: Inset - A single-line sunken border. InsetDouble - A double-line sunken border. None - No borders. Outset - A single-line raised border. Outset Double - A double-line raised border. OutsetPartial - A single-line border containing a raised portion. Single - A single-line border. ColumnCount - Determines the number of columns in the table. ColumnStyles - A collection of column styles, one for each column in the TableLayoutPanel control. Controls - Gets the collection of controls contained within the control. GrowStyle - Determines whether the control should expand to accommodate new cells when all existing cells are occupied. A value from the TableLayoutPanelGrowStyle enumeration is required, the default value is AddRows: AddColumns - The TableLayoutPanel gains additional columns after it is full. AddRows - The TableLayoutPanel gains additional rows after it is full. FixedSize - The TableLayoutPanel does not allow additional rows or columns after it is full. RowCount - Determines the number of rows in the table. RowStyles - A collection of row styles, one for each row in the TableLayoutPanel control.

Example

This dialog allows you to edit the SizeType property of each of the Columns and Rows in the TableLayoutPanel. The SizeType property determines how the Height (RowStyle) or Width (ColumnStyle) should be interpreted. A value from the SizeType enumeration is required, the default value is Percent: Absolute - The row or column should be sized to an exact number of pixels. AutoSize - The row or column should be automatically sized to share space with its peers. Percent - The row or column should be sized as a percentage of the parent container.

Adding a TableLayoutPanel manually ' Create TableLayoutPanel Dim tlp As New TableLayoutPanel() ' Set the BorderStyle to Inset tlp.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset ' Grid has two columns tlp.ColumnCount = 2 ' Grid has two rows tlp.RowCount = 2 ' If grid is full add extra cells by

adding column tlp.GrowStyle = TableLayoutPanelGrowStyle.AddColumns ' Padding (pixels)within each cell (left, top, right, bottom) tlp.Padding = New Padding(1, 1, 4, 5) ' Add TableLayoutPanel to the Forms controls Me.Controls.Add(tlp) Adding controls manually Adding a control to a TableLayoutPanel at run time can be done in a couple of ways. Simply using the Add method with just the name of the control adds the control to the first available cell. ' Create buttons Dim button1 As New Button() button1.Text = "Click Me" ' Add buttons to TableLayoutPanel tlp.Controls.Add(button1)

Panel Control
The Panel control is a container for other controls, customarily used to group related controls. Panels are used to subdivide a form by function, giving the user a logical visual cue of control grouping.

Useful properties AutoScroll - This property when set to true, allows scroll bars to be displayed. BackColor - The background color of the Panel is defaulted to System.Drawing.SystemColors.Control, but this can be set to any color you like. BackgroundImage - Instead of a single color, an image can be displayed as the background. BorderStyle - This property determines if the panel is outlined with no visible border (None), a plain line (FixedSingle), or a shadowed line (Fixed3D). Controls - Gets the collection of controls contained within the control. Enabled - if this property is set to false, the controls contained within the Panel will also be disabled. TabIndex - Gets or sets the tab order of the control within its container. (inherited from Control) TabStop - Gets or sets a value indicating whether the user can give the focus to this control using the TAB key.

Add a control to a Panel manually Public Sub CreateMyPanel() Dim panel1 As New Panel() Dim textBox1 As New TextBox() Dim label1 As New Label() ' Initialize the Panel control. panel1.Location = New Point(56, 72) panel1.Size = New Size(264, 152) ' Set the Borderstyle for the Panel to three-dimensional. panel1.BorderStyle =

System.Windows.Forms.BorderStyle.Fixed3D ' Initialize the Label and TextBox controls. label1.Location = New Point(16, 16) label1.Text = "label1" label1.Size = New Size(104, 16) textBox1.Location = New Point(16, 32) textBox1.Text = "" textBox1.Size = New Size(152, 20) ' Add the Panel control to the form. Me.Controls.Add(panel1) Panel. ' Add the Label and TextBox controls to the

panel1.Controls.Add(label1) panel1.Controls.Add(textBox1) End Sub

Split Container Control


This control is an advance window's control or it is an extended version of old splitter control. You can place it at form horizontally or vertically by specifying Orientation property each represents left/top and right/bottom panels respectively. The SplitContainer control can be thought of as a composite control; effectively it is two Panel controls separated by a movable bar (also known as a splitter bar). When the mouse pointer is over the bar, the pointer changes shape to show that the bar can be moved. Useful properties AutoScroll: This property when set to true, allows scroll bars to be displayed. BackColor: The background color of the SplitContainer is defaulted to System.Drawing.SystemColors.Control, but this can be set to any color you like. The whole of the SplitContainer changes color, however, each Panel can have its own background color. BackgroundImage: Instead of a single color, an image can be displayed as the background. The image only appears in the splitter bar. BorderStyle: This property determines if the panel is outlined with no visible border (None), a plain line (FixedSingle), or a shadowed line (Fixed3D). Dock: Determines which SplitContainer borders are attached to the edges of the container. When a SplitContainer control is dropped onto a container, this property defaults to Fill. FixedPanel: Determines which SplitContainer panel remains the same size when the container is resized. This property takes a value from the FixedPanel enumeration, the default value is None: None: Specifies that neither SplitContainer.Panel1, SplitContainer.Panel2 is fixed. A Control.Resize event affects both panels. Panel1: Specifies that SplitContainer.Panel1 is fixed. A Control.Resize event affects only SplitContainer.Panel2. Panel2: Specifies that SplitContainer.Panel2 is fixed. A Control.Resize event affects only SplitContainer.Panel1.

IsSplitterFixed: Gets or sets a value indicating whether the splitter is fixed or movable. Orientation:Gets or sets a value indicating the Horizontal or Vertical orientation of the SplitContainer panels. Panel1: Gets the left panel of a vertical SplitContainer or the top panel of a horizontal SplitContainer. When you click on this property in the IDE properties pane, you can edit the properties of the underlying Panel. Panel1Collapsed: Determines whether Panel1 is collapsed or expanded. When this value is true, Panel1 is hidden and Panel2 expands to fill the SplitContainer. This property is mutually exclusive with Panel2Collapsed. Panel1MinSize: Determines the minimum distance in pixels of the splitter from the left or top edge of Panel1. Panel2: Gets the right panel of a vertical SplitContainer or the bottom panel of a horizontal SplitContainer. When you click on this property in the IDE properties pane, you can edit the properties of the underlying Panel. Panel2Collapsed: Determines whether Panel2 is collapsed or expanded. When this value is true, Panel2 is hidden and Panel1 expands to fill the SplitContainer. This property is mutually exclusive with Panel1Collapsed. Panel2MinSize: Determines the minimum distance in pixels of the splitter from the right or bottom edge of Panel2. SplitterDistance: Determines the location of the splitter, in pixels, from the left (Orientation = Vertical) or top (Orientation = Horizontal) edge of the SplitContainer. SplitterIncrement: Gets or sets a value representing the increment of splitter movement in pixels. SplitterRectangle: Gets the size and location of the splitter relative to the SplitContainer. SplitterWidth: Determines the width of the splitter in pixels.

DateTimePicker and Month Calendar


DateTimePicker DateTimePicker is ideal for choosing a single date and/or time value and requires the same amount of space as an ordinary drop-down list box. When the user clicks the drop-down button, a month calendar appears. The operation of the control from this point is exactly the same as the MonthCalendar control.

Useful properties BackColor - Indicates the background color of the DateTimePicker control. CustomFormat - Determines the custom date/time format string. DropDownAlign - Determines the alignment of the drop-down calendar on the DateTimePicker control. Takes a value of either Left or Right. ForeColor - Indicates the foreground color of the DateTimePicker control. Format - Determines the format of the date and time displayed in the control. MaxDate - Determines the maximum date and time that can be selected in the control. MaximumDateTime - Gets the maximum date value allowed for the DateTimePicker control. MinDate - Determines the minimum date and time that can be selected in the control. MinimumDateTime - Gets the minimum date value allowed for the DateTimePicker control. ShowCheckBox - Indicates whether a check box is displayed to the left of the selected date. ShowUpDown - Indicates whether a spin button control (also known as an up-down control) is used to adjust the date/time value. Value - Determines the date/time value assigned to the control.

Month Calendar The MonthCalendar control presents an intuitive graphical interface for users to view and set date information.

Useful properties AnnuallyBoldedDates - Determines the array of DateTime objects that determines which annual days are displayed in bold. BoldedDates - Contains the array of DateTime objects that determines which nonrecurring dates are displayed in bold. CalendarDimensions - Determines the number of columns and rows of months displayed. You can have multiple months displayed horizontally and vertically. FirstDayOfWeek - Determines the first day of the week as displayed in the month calendar. By default, Sunday is shown as the first day of the week. MaxDate - Determines the maximum allowable date. MaxSelectionCount - Determines the maximum number of days that can be selected in a month calendar control. MinDate - Determines the minimum allowable date. MonthlyBoldedDates - Contains the array of DateTime objects that determine which monthly days to bold. SelectionEnd - Determines the end date of the selected range of dates. SelectionRange - Determines the selected range of dates for a month calendar control. SelectionStart - Determines the start date of the selected range of dates. ShowToday - Indicates whether the date represented by the TodayDate property is displayed at the bottom of the control. ShowTodayCircle - Indicates whether today's date is identified with a circle or square. ShowWeekNumbers - Indicates whether the month calendar control displays week numbers (1-52) to the left of each row of days. SingleMonthSize - Gets the minimum size to display one month of the calendar. TitleBackColor - Indicates the background color of the title area of the calendar. TitleForeColor - Indicates the foreground color of the title area of the calendar. TodayDate - Determines the value that is used by MonthCalendar as today's date.

TodayDateSet - Gets a value indicating whether the TodayDate property has been explicitly set. TrailingForeColor - Indicates the color of days in months that are not fully displayed in the control.

Example

Code for DateTime Picker Control Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged label1.Text = "DateTimePicker Date: " + DateTimePicker1.Text End Sub Code for Month Calendar Control Private Sub MonthCalendar1_DateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DateRangeEventArgs) Handles MonthCalendar1.DateChanged label2.Text = "Month Calender Date : " & MonthCalendar1.SelectionStart.ToLongDateString()

End Sub

NumericUpDown Control
This control is a simple way to give the user a way to select a number that falls between a minimum and a maximum value. The numeric value can be incremented or decremented by clicking the up or down buttons of the control. The user can also enter in a value. NumericUpDown control is controlled by four integer properties: Minimum, Maximum- Both defines the minimum and maximum values of the control ValueThis shows the current value of the control. Increment- The Increment property defines the amount by which the current value is incremented or decremented when the user clicks the up or down arrow buttons.

ValueChanged Event This event occurs Value property can be changed in code, by clicking the up or down button, or by the user entering a new value that is read by the control. The new value is read when the user hits the ENTER key or navigates away from the control. If the user enters a new value and then clicks the up or down button, the ValueChanged event will occur twice.

ProgressBar and Timer Control


For explaining Progressbar control we have link it with event so that the value of progress bar can increase, so here i have chosen timer control. And the the value of progressbar control is increment with timer control tick event. Progress bar control is used to hide the backend process so that user can aware of time consumed by back process of that application.

Code for Timer Control Tick Event Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick progressBar1.Visible = True progressBar1.Value = progressBar1.Value + 5 label3.Visible = True label3.Text = "Please Wait While we are checking Authentication..." If progressBar1.Value = progressBar1.Maximum Then If (textBox1.Text = "r4r") AndAlso (textBox2.Text = "r4r") Then Timer1.Enabled = False progressBar1.Visible = False label3.Text = "Welcome!! you are Authorised User." progressBar1.Enabled = False progressBar1.Value = 0 groupBox1.Visible = False Else progressBar1.Enabled = False

Timer1.Enabled = False progressBar1.Visible = False progressBar1.Value = 0 label3.Text = "Sorry!! Username or Password is Wrong." End If End If End Sub Make Progressbar Control Visible Property "false". Make timer enabled property true on "OK" button click. timer1.Enabled = True

ToolTip Control
ToolTip Control Provides the information to user when user moves mouse pointer over control. Like shown in below picture.

Adding ToolTip on Controls Step-1: Drap and drop tooltip control from toolbox to your form in which you want to add .

Step-2: Set the property of ToolTip as shown in below picture.

Step-3: Add tool tip on control in which you want to add. in above picture i have added ToolTip on textbox control. For this just simple type text on tooltip on ToolTip1 control: " Enter user name". Like in below picture.

TreeView Control
TreeView Control is used for showing hierarchical structured data visually e.g.. XML. Example for TreeView Control In shown Below -This is image of Explorer in Windows that show files and folder in tree view.

Working With TreeView Control Drag and drop TreeView Control from toolbox, Like shown in below image.

In following example I have taken a tree list view of colleges name for this i have taken ContextMenuChild and Parent for adding nodes. And you can also add by on clicking add child button and add sibling event. Code for Add Child is given Below

Private Sub buttonAddChild_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonAddChild.Click If textBox1.Text <> "" Then AddChildToTheNode() Else MessageBox.Show("Enter the Node Text to be added") textBox1.Focus() End If End Sub Private Sub AddChildToTheNode() Dim tnode As New TreeNode(textBox1.Text) treeView1.SelectedNode.Nodes.Add(tnode) treeView1.ExpandAll() If treeView1.SelectedNode.Nodes.Count > 1 AndAlso treeView1.SelectedNode.ForeColor <> Color.Blue Then treeView1.SelectedNode.ForeColor = Color.Brown End If End Sub Code for Menu Item Click If textBox1.Text <> "" Then AddChildToTheNode() Else MessageBox.Show("Enter the Node Text to be added") textBox1.Focus() End If Code for Add Sibling Private Sub btnAddSibling_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btnAddSibling.Click If textBox1.Text <> "" Then AddSiblingToTheNode() Else MessageBox.Show("Enter the Node Text to be added") textBox1.Focus() End If End Sub Private Sub AddSiblingToTheNode() Dim tnode As New TreeNode(textBox1.Text) tnode.ForeColor = Color.Brown treeView1.SelectedNode.Parent.Nodes.Add(tnode) End Sub

Code For Deleting Child and Sibling. Private Sub buttonDeleteParent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonDeleteParent.Click DeleteNode() End Sub Private Sub DeleteNode() If treeView1.SelectedNode.Nodes.Count = 0 Then treeView1.SelectedNode.Remove() Else MessageBox.Show("First Remove all the child nodes") End If End Sub

Menus and ToolBar Controls


In this category following controls comes MenuStrip ToolStrip controls ContextMenusStrip StatusStrip

MenuStrip Control Useful properties

AllowItemReorder (Inherited from ToolStrip) - Gets or sets a value indicating whether drag-and-drop and item reordering are handled privately by the MenuStrip class. Set the property to true to allow reordering. At run time, the user holds down the ALT key and the left mouse button to drag a ToolStripMenuItem to a different location on the MenuStrip. AllowMerge (Inherited from ToolStrip) - When enabled, this property allows multiple-document interface (MDI) children to combine their respective menus in the MDI parent. Dock - Gets or sets which edge of the parent container a MenuStrip is docked to.

LayoutStyle - Gets or sets a value indicating how the MenuStrip lays out its items. Padding (Inherited from Control) - Gets or sets the control's internal spacing characteristics. The default values for Padding are reasonably close to Windows user interface guidelines. RenderMode - Gets or sets the painting styles to be applied to the MenuStrip. TextDirection (Inherited from ToolStrip) - Allows the text to be rotated within the button. The property takes one of four values contained in the ToolStripTextDirection enumeration. Horizontal - Specifies horizontal text orientation. Inherit - Specifies that the text direction is inherited from the parent control. (Default state) Vertical270 - Specifies that text is to be rotated 270 degrees clockwise. Vertical90 - Specifies that text is to be rotated 90 degrees clockwise.

ToolStrip Control The ToolStrip is a container for holding different types of controls that are derived from ToolStripItem. In the example that we just created, the ToolStrip holds a selection of buttons which are instances of ToolStripButton. Other items that can be held within the ToolStrip are:

ToolStripSplitButton ToolStripDropDownButton ToolStripLabel ToolStripProgressBar ToolStripSeparator ToolStripComboBox ToolStripTextBox

A ToolStrip appears by default as Office-style with a flat look. Windows XP themes are supported however the painting of the control may be overridden. Adding standard Items in ToolStrip

ContextMenusStrip Control Applications use two kinds of menusmain menus and context menus. Context menus are "pop up" menus that provide additional options, usually when the user right-clicks a part of the window. Adding Menus in ContextMenusStrip

At runtime, your ContextMenusStrip wont appear. You have two choices to display it. The easiest approach is to associate it with another control by setting the Control.ContextMenuStrip property to your ContextMenusStrip object. When the user rightclicks the control, your context menu appears automatically. As shown in Picture.

Background Worker Control


The BackgroundWorker Component allows a form to run an operation asynchronously. This is very useful when we deal with such kind of operations as database transactions, image downloads etc.

Adding DoWork The DoWork method is like any other event handler. Here we must look at the VB view of your file, where we will see the DoWork method. You should see that the backgroundWorker1_DoWork event is generated when you double-click on DoWork. For testing, let's add a Thread.Sleep command there. The Thread.Sleep method will pause the execution of the BackgroundWorker, but does not consume the entire CPU.

Code For DoWork Event is Given Below Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork Dim argumentTest As TestObject = TryCast(e.Argument, TestObject) Thread.Sleep(100) argumentTest.OneValue = 12 argumentTest.TwoValue = 14 e.Result = argumentTest End Sub

Creating Slice Chart in windows using VB.Net


Introduction: In VB.Net with the help of GDI classes we can design or draw charts or graphs is a very efficient manner in our projects. Charts are the pictorial representation of the data through chart one can easily judge or see the ups and down or profit loss in other words we can say we can show the groth rate of any business through chart. Slice Charts are consider as cutting a cake into slices based on the weight. In this chart, angle of slice is linearly proportional to weight. With the help of FillPie() method slice chart can be designed. Private Function FillPie(brush As Brush, x As Integer, y As Integer, width As Integer, height As Integer, startAngle As Integer, _ sweepAngle As Integer) As Void End Function FillPie function is used to fill as ellipse if sweep angle is 360. To make it a circle, we make height and width both equal to diameter of circle. Brush brush: It is a brush object used to fill the Pie. Int x: x co-ordinate of upper left corner of the bounding rectangle that defines the ellipse from which the pie section comes. So if the x co-ordinate of center of our circle is x0 and radius is r: - x = x0 r; Int y: Same as x- co-ordinate. y = y0 r; Int width: Width of bounding rectangle that defines the ellipse from which the pie section comes. width = 2*radius; Int startAngle: Angle in degrees measured clockwise from the x-axis to the first side of the pie section. So we start with 0 degrees and increment it with the sweepAngle for the next slice to start right after the end of previous slice. Int sweepAngle: Angle in degrees measured clockwise from the startAngle parameter to the second side of pie section. So this is span of angle based on weight. So 360 degrees is proportionally divided into 8 parts based on the weight. Example: To draw slice chart we have to take an array named alweight. Code for on Form Load: Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load alWeight = New Integer() {13, 23, 33, 15, 20, 10, 4, 11} End Sub Code for DrawSliceChart method Private Sub Dim Dim Dim Dim DrawSliceChart(e As PaintEventArgs, alWeight As Integer()) numberOfSections As Integer = alWeight.Length x0 As Integer = 100 y0 As Integer = 100 radius As Integer = 100

Dim startAngle As Integer = 0 Dim sweepAngle As Integer = 0 Dim height As Integer() = New Integer(numberOfSections - 1) {} Dim total As Integer = SumOfArray(alWeight) Dim rnd As New Random() Dim brush As New SolidBrush(Color.Aquamarine) Dim pen As New Pen(Color.Black) For i As Integer = 0 To numberOfSections - 1 brush.Color = Color.FromArgb(rnd.[Next](200, 255), rnd.[Next](255), rnd.[Next](255), rnd.[Next](255)) If i = numberOfSections - 1 Then sweepAngle = 360 - startAngle Else sweepAngle = (360 * alWeight(i)) \ total End If e.Graphics.FillPie(brush, x0 - height(i), y0 - height(i), 2 * radius, 2 * radius, startAngle, _ sweepAngle) e.Graphics.DrawPie(pen, x0 - height(i), y0 - height(i), 2 * radius, 2 * radius, startAngle, _ sweepAngle) startAngle += sweepAngle brush.Color = Color.FromKnownColor(KnownColor.Black) Next End Sub Code for SumofArray method Private Shared Function SumOfArray(intArray As Integer()) As Integer Dim sum As Integer = 0 For i As Integer = 0 To intArray.Length - 1 sum += intArray(i) Next Return sum End Function Difference between FillPie( ) and DrawPie( ) The only difference between DrawPie and FillPie is that it takes Pen object instead of Brush. Calling DrawSliceChart Method Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint DrawSliceChart(e, alWeight) End Sub

Introduction of Socket
A Socket is an End-Point for communication link between two programs (Server Program and Client Program ) running on the same network .Socket is bidirectional. We have to write two programs for implementing a socket application in VB.Net. Server Socket Program ( Server ) Client Socket Program ( Client ) .

In VB.Net network programming can be done by using namespaces like System.Net and System.Net.Sockets . The classes and methods of these namespaces can communicate across the network. The communication can be either connection oriented or connectionless. They can also be either stream oriented or data-gram based. Server Socket Program- Server program running on a computer has a socket that bound to a Port Number on the same computer and listening to the client's incoming requests. Client Socket Program- Client program have to know the IP Address ( Hostname ) of the computer that the VB.Net Server Socket Program resides and the Port Number assign for listening for client's request .

Code for Server Socket Program Module Module1 Sub Main() Dim serverSocket As New TcpListener(8888) Dim requestCount As Integer = 0 Dim clientSocket As TcpClient = Nothing serverSocket.Start() Console.WriteLine(" >> Server Started") clientSocket = serverSocket.AcceptTcpClient() Console.WriteLine(" >> Accept connection from client") requestCount = 0 While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = clientSocket.GetStream() Dim bytesFrom As Byte() = New Byte(10024) {} networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$")) Console.WriteLine(" >> Data from client " & dataFromClient) Dim serverResponse As String = "Server response " & Convert.ToString(requestCount) Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Flush() Console.WriteLine(" >> " & serverResponse) Catch ex As Exception Console.WriteLine(ex.ToString()) End Try End While clientSocket.Close()

serverSocket.[Stop]() Console.WriteLine(" >> exit") Console.ReadLine() End Sub End Module

Code for Client Socket Program For creating Client design a Client using windows application. Server is console application but client is windows application. Server will give response when client request to sending data or connecting with server.

Namespace New_Client Public Partial Class Form1 Inherits Form Private clientSocket As New System.Net.Sockets.TcpClient() Public Sub New() InitializeComponent() End Sub As EventArgs) 8888) End Sub Public Sub msg(mesg As String) textBox1.Text = textBox1.Text + Environment.NewLine + " >> " & mesg End Sub Private Sub button1_Click(sender As Object, e As EventArgs) Dim serverStream As NetworkStream = clientSocket.GetStream() Dim outStream As Byte() = System.Text.Encoding.ASCII .GetBytes("Message from Client$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() Dim inStream As Byte() = New Private Sub Form1_Load(sender As Object, e msg("Client Started") clientSocket.Connect("127.0.0.1",

Byte(10024) {}

serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize)) Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream) msg("Data from Server : " & returndata) End Sub End Class End Namespace

First execute the Server Socket Program and then Client Socket Program as shown in above pictures-

On Click to button "Send data to server" the data will send to server.

Creating Bar Chart in windows using VB.Net


Introduction: For making bar chart we will make use of DrawRectangle in built function. because we have to first create a big rectangle defining the boundary of bar graphs. Parameters of DrawRectangle is : 1. Pen This defines the color and style of border 2. Rectangle Rectangle object to be created Private Sub New(x As Integer, y As Integer, width As Integer, height As Integer) End Sub X and y are the co-ordinates of top left corner of rectangle. Width and height are width and height of rectangle. Height = (weight of current array element *height of outer rectangle )/ maximum weight. X coordinate is incremented by width of bars everytime a new bar is created. Y co-ordinate is calculated by the following formula: y = y coordinate of outer rectangle + height of outer rectangle height of bar Code for DrawBarChart

Private Sub DrawBarChart(ByVal e As PaintEventArgs, ByVal alWeight As Integer()) Dim numberOfSections As Integer = alWeight.Length Dim lengthArea As Integer = 330 Dim heightArea As Integer = 280 Dim topX As Integer = 20 Dim topY As Integer = 20 Dim maxWeight As Integer = MaxValue(alWeight) Dim height As Integer() = New Integer(numberOfSections - 1) {} Dim total As Integer = SumOfArray(alWeight) Dim rnd As New Random() Dim brush As New SolidBrush(Color.Aquamarine) Dim pen As New Pen(Color.Gray) Dim rec As New Rectangle(topX, topY, lengthArea, heightArea) e.Graphics.DrawRectangle(pen, rec) pen.Color = Color.Black Dim smallX As Integer = topX Dim smallY As Integer = 0 Dim smallLength As Integer = (lengthArea \ alWeight.Length) Dim smallHeight As Integer = 0 For i As Integer = 0 To numberOfSections - 1 brush.Color = Color.FromArgb(rnd.[Next](200, 255), rnd.[Next](255), rnd.[Next](255), rnd.[Next] (255)) smallHeight = ((alWeight(i) * heightArea) \ maxWeight) smallY = topY + heightArea - smallHeight Dim rectangle As New Rectangle(smallX, smallY, smallLength, smallHeight) e.Graphics.DrawRectangle(pen, rectangle) e.Graphics.FillRectangle(brush, rectangle) brush.Color = Color.FromKnownColor(KnownColor.Black) e.Graphics.DrawRectangle(pen, rectangle) smallX = smallX + smallLength Next End Sub

What is DLL?
A dynamic linking library (DLL) is linked to your program at run time. DLL is similar to an EXE but is not directly executable. Functions in the dll are called from the main exe. It provides a way to split what would be a very large exe into an exe plus one or more dlls. Creating DLL in VB.Net To creating DLL in VB.Net just follow next stepsGoto File -> New Project then choose Class Library you will see window like below.

Here i am going to show DLL for addition, subtraction, multiplication, and division. Code for this is given belowPublic Class Class1 Public Function add(ByVal x As Integer, ByVal y Integer) As Integer Dim z As Integer = x + y Return z End Function Public Function [sub](ByVal x As Integer, ByVal Integer) As Integer Dim z As Integer = x - y Return z End Function Public Function mul(ByVal x As Integer, ByVal y Integer) As Integer Dim z As Integer = x * y Return z End Function Public Function div(ByVal x As Integer, ByVal y Integer) As Integer Dim z As Integer = x \ y

As

y As

As

As

Return z End Function End Class After this Build this class by pressing F6 and dll will generate this class library now you can use this in any other application where you want to use this dll. Using DLL in VB.Net Application For using DLL in application you have to make add reference of the dll that you

Design the form as shown in below picture

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim c1 As ClassLibrary1.Class1 = New Class1() Dim result As Integer = c1.add(Integer.Parse(textBox1.Text), Integer.Parse(textBox2.Text)) textBox3.Text = result.ToString() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim c2 As ClassLibrary1.Class1 = New Class1() Dim result As Integer = c2.[sub] (Integer.Parse(textBox1.Text), Integer.Parse(textBox2.Text)) textBox3.Text = result.ToString() End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Dim c3 As ClassLibrary1.Class1 = New Class1() Dim result As Integer = c3.mul(Integer.Parse(textBox1.Text), Integer.Parse(textBox2.Text)) textBox3.Text = result.ToString() End Sub Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click Dim c4 As ClassLibrary1.Class1 = New Class1() Dim result As Integer = c4.div(Integer.Parse(textBox1.Text), Integer.Parse(textBox2.Text)) textBox3.Text = result.ToString() End Sub

How to Access IP Address of LAN Connected Computers


In VB.Net with the help of Namespace System.Net.Sockets and System.Net we can build an application through which we can find ID address of the machine connected with LAN. Program code is given belowSystem.Net.IPHostEntry - Provides a container class for internet host address information . Dns.Resolve("strhostname")- Resolve a DNS hostname or IP Address to an System.Net.IPHostEntry instance. Console.ReadKey()- Obtains the next character or function key pressed by the user. The pressed key is optimally displayed in the console window. Imports System.Net Imports System.Net.Sockets Module Module1 Sub Main() Dim strHost As String Console.Write("Input host : ") strHost = Console.ReadLine() Dim IPHost As IPHostEntry = Dns.Resolve(strHost) Console.WriteLine(IPHost.HostName) Dim address As IPAddress() = IPHost.AddressList Console.WriteLine("List IP {0} :", IPHost.HostName) For i As Integer = 0 To address.Length - 1 ' output list of IP address Console.WriteLine(address(i)) Next Console.ReadKey() End Sub End Module

IP Address of Machine-02

IP Address of Machine-01

How to get IP Address of Websites in VB.Net application


In VB.Net with the help of Namespace System.Net.Sockets and System.Net we can build an application through which we can find ID address of the websites.

Program code is given belowIPHostEntry - Provides a container class for internet host address information . Dns.GetHostEntry("Hostname")- Resolve a DNS hostname or IP Address to an System.Net.IPHostEntry instance. Imports System.Net Imports System.Net.Sockets Module Module1 Sub Main() Dim HostName As [String] Console.WriteLine("Enter Web Address:") HostName = Console.ReadLine() Console.WriteLine("Looking up: {0}", HostName) Dim NameToIpAddress As IPHostEntry NameToIpAddress = Dns.GetHostEntry(HostName) Dim AddressCount As Integer = 0 For Each Address As IPAddress In NameToIpAddress.AddressList Console.WriteLine("IP Address {0}: {1}", System.Threading.Interlocked.Increment(AddressCount), Address.ToString()) Next Console.ReadLine() End Sub End Module

IP Address of Gmail.com

IP Address of Facebook.com

Synchronization in VB.Net
Introduction of Synchronization- Synchronization is particularly important when threads access the same data; its surprisingly easy to run aground in this area. Synchronization constructs can be divided into four categories: Simple blocking methods Locking constructs Signaling constructs No blocking synchronization constructs

Synchronization in Threads- Synchronization is needed in thread when we have multiple threads that share data, we need to provide synchronized access to the data. We have to deal with synchronization issues related to concurrent access to variables and objects accessible by multiple threads at the same time. Imports System.Threading Module Module1 Class Program Shared Sub Main() Console.WriteLine("-----> Multiple Threads ---->") Dim p As New Printer() Dim Threads As Thread() = New Thread(2) {} For i As Integer = 0 To 2 Threads(i) = New Thread(New

ThreadStart(AddressOf p.PrintNumbers)) Threads(i).Name = "Child " & i Next For Each t As Thread In Threads t.Start() Next Console.ReadLine() End Sub End Class Class Printer Public Sub PrintNumbers() For i As Integer = 0 To 4 Thread.Sleep(100) Console.Write(i & ",") Next Console.WriteLine() End Sub End Class End Module

Why we use Lock keyword- lock(object) is used to synchronize the shared object. Syntax: SyncLock objecttobelocked objecttobelocked.somemethod() End SyncLock objecttobelocked is the object reference which is used by more than one thread to call the method on that object.

The lock keyword requires us to specify a token (an object reference) that must be acquired by a thread to enter within the lock scope.

Using of Monitor- The lock scope actually resolves to the Monitor class after being processed by the VB.Net compiler. Lock keyword is just a notation for Imports System.Threading.Monitor class. Imports System.Threading Imports System.Threading.Monitor Module Module1 Class Program Shared Sub Main(ByVal arg As String()) Console.WriteLine(" -----> Multiple Threads ----->") Dim p As New Printer() Dim Threads As Thread() = New Thread(2) {} For i As Integer = 0 To 2 Threads(i) = New Thread(New ThreadStart(AddressOf p.PrintNumbers)) Threads(i).Name = "Child " & i Next For Each t As Thread In Threads t.Start() Next Console.ReadLine() End Sub End Class Class Printer Public Sub PrintNumbers() Monitor.Enter(Me) Try For i As Integer = 0 To 4 Thread.Sleep(100) Console.Write(i & ",") Next Console.WriteLine() Finally Monitor.[Exit](Me) End Try End Sub End Class End Module

Creating Word document using VB.Net


Create a new windows application project and add a button to it. On click of that button, we will create a new document(word) and write a simple text in it. To create a word document using VB.Net we need to first reference the following DLL(com)..

After That Write Code in .CS File: Imports Imports Imports Imports Imports Imports Imports Imports System.Collections.Generic System.ComponentModel System.Data System.Drawing System.Linq System.Text System.Windows.Forms Word = Microsoft.Office.Interop.Word

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim missing As Object = System.Reflection.Missing.Value Dim Visible As Object = True Dim start1 As Object = 0 Dim end1 As Object = 0 Dim WordApp As New Word.ApplicationClass() Dim adoc As Word.Document = WordApp.Documents.Add(missing, missing, missing, missing) Dim rng As Word.Range = adoc.Range(start1, missing) Try rng.Font.Name = "Georgia" rng.InsertAfter("Hiiiiiiiiiiii I m Aditya!") Dim filename As Object = "C:\MyWord.doc" adoc.SaveAs(filename, missing, missing, missing, missing, missing, _ missing, missing, missing, missing, missing, missing, _ missing, missing, missing, missing) WordApp.Visible = True Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub End Class Output:

How to Add Manually CheckBox in VB.Net


You can add a CheckBox to a form at run time in the following manner. Code for Add mannualy CheckBox in VB.Net: Imports Imports Imports Imports Imports Imports Imports System.Collections.Generic System.ComponentModel System.Data System.Drawing System.Linq System.Text System.Windows.Forms

Public Class Form1 Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

If TypeOf sender Is CheckBox Then Dim checkbox As CheckBox = TryCast(sender, CheckBox) If checkbox.Checked Then checkbox.Text = "Checked" AddCheckBox() Else checkbox.Text = "UnChecked" End If End If End Sub Public Sub AddCheckBox() Dim chkBox As New CheckBox() Me.Controls.Add(chkBox) chkBox.Location = New Point(100, 100) chkBox.AutoCheck = True chkBox.Text = "New CheckBox" chkBox.Checked = True chkBox.CheckState = CheckState.Checked End Sub End Class

Out Put:

How to Change The Color of Specific Word in Rich textbox using VB.Net
.vbCode: Imports Imports Imports Imports System.Collections.Generic System.ComponentModel System.Data System.Drawing

Imports System.Linq Imports System.Text Imports System.Windows.Forms Public Class Form1 Private Shared Sub HighlightPhrase(ByVal box As RichTextBox, ByVal phrase As String, ByVal color As Color) Dim pos As Integer = box.SelectionStart Dim s As String = box.Text Dim ix As Integer = 0 While True Dim jx As Integer = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase) If jx < 0 Then Exit While End If box.SelectionStart = jx box.SelectionLength = phrase.Length box.SelectionColor = color ix = jx + 1 End While box.SelectionStart = pos box.SelectionLength = 0 End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click HighlightPhrase(RichTextBox1, "a", Color.Red) HighlightPhrase(RichTextBox1, "b", Color.Blue) End Sub End Class Design Output:

Reading/Writing/Appending a Text File, Using VB.Net

.vb Code: Imports System.Collections.Generic Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Linq Imports System.Text Imports System.Windows.Forms Imports System.IO Public Class Form1 Private Sub file_write() Dim path As String = "C:\ash" ' Parent Directory Dim name As String = richTextBox1.Text Dim ext As String = ".txt" Dim fname As String = path & name & ext Dim file1 As New FileInfo(fname) Dim sw As StreamWriter = file1.CreateText() sw.WriteLine("This is a demo for writing to a text file") 'Writing a string directly to the file sw.WriteLine(richTextBox1.Text) ' Writing content read from the textbox in the form sw.Close() End Sub Private Sub file_read() Dim path As String = "C:\" ' Parent Directory Dim name As String = richTextBox1.Text Dim ext As String = ".txt" Dim fname As String = path & name & ext Dim readcontent As String Dim file1 As New FileInfo(fname) Dim sr As New StreamReader(fname) readcontent = sr.ReadToEnd() ' Reading content from the file and storing to a string sr.Close() richTextBox1.Text = readcontent ' Display contents in a textbox in the form End Sub Private Sub file_append() Dim path As String = "C:\" ' Parent Directory Dim name As String = richTextBox1.Text Dim ext As String = ".txt" Dim fname As String = path & name & ext ' FileInfo file1 = new FileInfo(fname);

Dim sw As StreamWriter = File.AppendText(fname) sw.WriteLine("This is a demo for appending text content to a file") ' Writing a string directly to the file sw.WriteLine(richTextBox1.Text) sw.Close() End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click file_read() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click file_append() End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click file_write() End Sub End Class Output:

How to Find Max Value of X, Y ,Z From Text file Using VB.Net

.vb CODE: Imports System.Collections.Generic Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Linq Imports System.Text Imports System.Windows.Forms Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Lines As String() = File.ReadAllLines("TextFile1.txt") Dim maxZ As Integer = 0 For Each line As String In Lines Dim SplitString As String() = line.Split(" "c) If SplitString.Length > 2 Then Try If Integer.Parse(SplitString(2)) > maxZ Then maxZ = Integer.Parse(SplitString(2)) End If Catch End Try End If Next TextBox2.Text = maxZ.ToString() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim Lines As String() = File.ReadAllLines("TextFile1.txt") Dim maxX As Integer = 0 For Each line As String In Lines Dim SplitString As String() = line.Split(" "c) If SplitString.Length > 3 Then Try If Integer.Parse(SplitString(3)) > maxX Then maxX = Integer.Parse(SplitString(3)) End If Catch End Try End If

Next TextBox3.Text = maxX.ToString() End Sub Private Sub btnFindMaxY_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFindMaxY.Click Dim Lines As String() = File.ReadAllLines("TextFile1.txt") Dim maxY As Integer = 0 For Each line As String In Lines Dim SplitString As String() = line.Split(" "c) If SplitString.Length > 1 Then Try If Integer.Parse(SplitString(1)) > maxY Then maxY = Integer.Parse(SplitString(1)) End If Catch End Try End If Next TextBox1.Text = maxY.ToString() End Sub End Class Design:

Create Text file Like This:

Output:

Multiple Colored Texts in RichTextBox using VB.Net


Actually This Application tells how to enter values in a richtextbox with multiple color texts. There is a property to set colored text by using SelectionText. Richtextbox has the properties of SelectionFont, SelectionColor and SelectedText. Setting the values for these properties makes multiple colors in our richtextbox. I just tried to create it as a sample application and it is done. .vb Code: Imports System.Collections.Generic Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Linq Imports System.Text Imports System.Windows.Forms Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim font As New Font("Tahoma", 8, FontStyle.Regular) RichTextBox1.SelectionFont = font RichTextBox1.SelectionColor =

Color.Red RichTextBox1.SelectedText = Environment.NewLine + textBox1.Text End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim font As New Font("Tahoma", 8, FontStyle.Regular) RichTextBox1.SelectionFont = font RichTextBox1.SelectionColor = Color.Green RichTextBox1.SelectedText = Environment.NewLine + textBox1.Text End Sub End Class Design Output:

Storing Database Connection Strings in App.Config


.NET Framework 2.0 added a separate configuration section in both Windows Application configuration (App.config) and Web Application configuration (Web.config) file. Developers can use these section to store connection string information such as a connection string name or provider type etc. In the following tutorial I will show you how you can store and retrieve connection string information in .NET Windows Application using VB.Net. The following code shows how you can store connection strings in App.config file.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="name" value="provider=microsoft.jet.oledb.4.0;data source=E://invent.mdb"/> </appSettings> </configuration> In the code behind you should import the following namespace: Imports System.Configuration Then retreive the value from the App.Config by the following code: Dim con As String = ConfigurationSettings.AppSettings("name").ToString() Example: Imports Imports Imports Imports Imports Imports Imports Imports Imports System.Collections.Generic System.ComponentModel System.Data System.Drawing System.Linq System.Text System.Windows.Forms System.Configuration System.Data.OleDb

Public Class Form1 Dim con As String = ConfigurationSettings.AppSettings("name").ToString() Dim mycon As OleDbConnection Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click mycon = New OleDbConnection(con) mycon.Open() Dim cmd1 As New OleDbCommand("select location from purchasing ", mycon) Dim dr As OleDbDataReader = cmd1.ExecuteReader() While dr.Read() textBox1.Text = dr(0).ToString() End While mycon.Close() End Sub End Class

ASP.Net Basic Tutorial (VB.Net Based) ASP.net Basic Tutorials with Examples

1. Introduction of ASP.NET 2. Life Cycle of Web pages And Types Of Control in Asp.net 3. State Management in Asp.net And how to Implement Viewstate 4. Cookies in Asp.net 5. How to Implement Query String in Asp.net 6. Server Side State Management 7. Master Page In Asp.net 8. Introduction Of Gridview Control 9. Simple Databind In Gridview Control 10. Simple Code For Edit Update And Delete In Gridview 11. All Gridview Code In Asp.net 12. Validation Control in Asp.net 13. RequiredFieldvalidator in Asp.net 14. Compare Validator 15. RegularExpressionValidator control in Asp.net 16. CustomValidator control in Asp.net 17. Summary Validation Control in Asp.net 18. Label Control 19. TextBox Control 20. Button Control 21. ImageButton Control 22. Hyperlink 23. Literal 24. LinkButton Control 25. DropDownList Control Introduction of ASP.NET
ASP.NET is the next generation ASP, but it's not an upgraded version of ASP. ASP.NET is an entirely new technology for server-side scripting. ASP.NET is a part of the Microsoft .NET framework, and a powerful tool for creating dynamic and interactive web pages. ASP.NET is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server ASP.NET is a Microsoft Technology. ASP stands for Active Server Pages ASP.NET is a program that runs inside IIS. IIS (Internet Information Services) is Microsoft's Internet server. IIS comes as a free component with Windows servers. IIS is also a part of Windows 2000 and XP Professional.

ASP.NET File
An ASP.NET file is just the same as an HTML file An ASP.NET file can contain HTML, XML, and scripts Scripts in an ASP.NET file are executed on the server An ASP.NET file has the file extension ".aspx"

Working of ASP.NET
When a browser requests an HTML file, the server returns the file. When a browser requests an ASP.NET file, IIS passes the request to the ASP.NET engine on the server. The ASP.NET engine reads the file, line by line, and executes the scripts in the file. Finally, the ASP.NET file is returned to the browser as plain HTML.

Difference Between ASP and ASP.NET


1. Code behind in asp. net allows separation of business logic from UI which is not possible in asp. 2. ASP. Net uses ADO .Net objects which are represented using XML and hence they are lightweight and can travel through firewalls. ASP uses ADO record sets which are binary COM objects heavier than ADO.Net counterparts and cannot travel through firewalls. 3. ASP.Net supports object oriented programming. ASP is procedural. 4. ASP.Net is compiled and hence performs better. ASP is pure scripting and hence interpreted at the time of page load. 5. ASP.Net has caching and exception handling which is not available with ASP. 6. ASP.NET has better language support, a large set of new controls, XML-based components, and better user authentication. 7. ASP.NET provides increased performance by running compiled code. 8. ASP.NET code is not fully backward compatible with ASP

Advantage of ASP.NET
1. ASP.NET drastically reduces the amount of code required to build large applications. 2. With built-in Windows authentication and per-application configuration, your applications are safe and secured. 3. It provides better performance by taking advantage of early binding, just-in-time compilation, native optimization, and caching services right out of the box. 4. The ASP.NET framework is complemented by a rich toolbox and designer in the Visual Studio integrated development environment. WYSIWYG editing, drag-anddrop server controls, and automatic deployment are just a few of the features this powerful tool provides. 5. Provides simplicity as ASP.NET makes it easy to perform common tasks, from simple form submission and client authentication to deployment and site configuration. 6. The source code and HTML are together therefore ASP.NET pages are easy to maintain and write. Also the source code is executed on the server. This provides a lot of power and flexibility to the web pages. 7. All the processes are closely monitored and managed by the ASP.NET runtime, so that if process is dead, a new process can be created in its place, which helps keep your application constantly available to handle requests. 8. It is purely server-side technology so, ASP.NET code executes on the server before it is sent to the browser. 9. Being language-independent, it allows you to choose the language that best applies to your application or partition your application across many languages. 10. ASP.NET makes for easy deployment. There is no need to register components because the configuration information is built-in.

11. The Web server continuously monitors the pages, components and applications running on it. If it notices any memory leaks, infinite loops, other illegal activities, it immediately destroys those activities and restarts itself. 12. Easily works with ADO.NET using data-binding and page formatting features. It is an application which runs faster and counters large volumes of users without having performance problems.

Life Cycle of ASP.NET


Page Life Cycle Events Page_Init: The server controls are loaded and initialized from the Web form's view state. it is basically used for initialized the object and control Page_Load: The server controls are loaded in the page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page. Page_PreRender: The application is about to render the page object. Page_Unload: The page is unloaded from memory. Page_Disposed: The page object is released from memory. This is the last event in the life of a page object. Page_Error: An unhandled exception occurs. Page_AbortTransaction: A transaction is aborted. Page_CommitTransaction: A transaction is accepted. Page_DataBinding: A server control on the page binds to a data source.

Control in ASP.NET
HTML Controls - Traditional HTML tags Web Server Controls - New ASP.NET tags Validation Server Controls - For input validation

HTML Server Controls


HTML server controls are HTML tags understood by the server. HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control. The id reference can be used to manipulate the server control at run time. Note: All HTML server controls must be within a <form> tag with the runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the server. It also indicates that the enclosed controls can be accessed by server scripts. DESIGN OF HTML CONTROL

<script language="javascript" type="text/javascript"> function Submit1_onclick() { alert("click me"); } </script> </head> <body> <form id="form1" runat="server"> <div> <input id="Text1" type="text" value="anil" /> <input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" /></div> </form> </body> </html>

Web Server Controls


Web server controls are special ASP.NET tags understood by the server. Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. However, Web server controls do not necessarily map to any existing HTML elements and they may represent more complex elements.

The syntax for creating a Web server control is:


<asp:control_name id="some_id" runat="server" /> DESIGN OF WEB SERVER CONTROL

.ASPX CODE
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div style="width: 246px; background-color: #66FFFF;"> Name&nbsp; <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="click me" /> <br /> <br /> </div> </form> </body> </html>

.VB CODE
Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = "wiliam" TextBox2.Text = "hello world" End Sub End Class Validation Server Controls DESIGN OF VALIDATION SERVER CONTROL

Validation server controls are used to validate user-input. If the user-input does not pass validation, it will display an error message to the user. .ASPX Code <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div style="width: 414px; background-color: #66FFFF;"> Name&nbsp; <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Blank are not allowed" SetFocusOnError="True"></asp:RequiredFieldValidator> <br /> &nbsp;Address&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextBox2_TextChanged"></asp:TextBox> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="click me" /> <br /> <br /> </div> </form> </body> </html>

.VB CODE
Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = "123" TextBox2.Text = "hello world"

Response.Write("hi display textbox 1 value" + TextBox1.Text) End Sub End Class

State Management in ASP.NET


State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

Types of State Management


Client Side State Management ASP.NET provides various client side state management options like Cookies, Query Strings (URL), Hidden fields, View State and Control state (ASP.NET 2.0).This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator (url), or a cookie. The techniques available to store the state information at the client computer. a. View State Asp .Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp .net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

Example of View state


Write code in .aspx page <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>ViewState</title> </head> <body> <form id="form1" runat="server"> <asp:TextBox runat="server" id="NameField" /> <asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" /> <asp:Button runat="server" id="RefreshPage" text="Just submit" /> <br /><br /> Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" /> </form>

</body> </html> .vb Code Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If ViewState("NameOfUser") IsNot Nothing Then NameLabel.Text = ViewState("NameOfUser").ToString() Else NameLabel.Text = "Not set yet..." End If End Sub End Class

Advantages
The main advantage of view state is persisting controls properties without any programming and memory will not be occupied on the client system or on the server system.

Disadvantage
The disadvantage can be considered as a lot amount of data transmission between client and server.

1. Control State If you create a custom control that requires view state to work

properly, you should use control state to ensure other developers dont break your control by disabling view state. 2. Hidden fields Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed. 3. Cookies Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site. 4. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

Cookies in ASP.NET
A cookie is a small bit of text file that browser creates and stores on your machine (hard drive). Cookie is a small piece of information stored as a string. Web server sends the cookie and browser stores it, next time server returns that cookie .Cookies are mostly used to store the information about the user. Cookies are stores on the client side .To store data in a cookie is not secure due to it's location at client end. Cookie was introduced with first version of Netscape navigator (that was 1.0).

Advantages
1. Cookies do not require any server resources since they are stored on the client. 2. Cookies are easy to implement. 3. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).

Disadvantages
1. Users can delete a cookies. 2. Users browser can refuse cookies ,so your code has to anticipate that possibility. 3. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.

.ASPX CODE
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default3.aspx.vb" Inherits="Default3" %> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <fieldset> <legend>rdfdf</legend> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Add" Width="70px" onclick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="View" Width="84px" onclick="Button2_Click" /> <br /> <br /> <asp:Label ID="Label1" runat="server" Text="" Width="138px"></asp:Label> </fieldset> </div> </form> </body> </html>

.CS CODE
Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender ByVal e As System.EventArgs) Handles Response.Cookies("MyCookie")("Data") ' To Create Cookies Response.Cookies("MyCookie")("Time")

As Object, Button1.Click = TextBox1.Text = DateTime.Now.ToString("G")

Response.Cookies("MyCookie").Expires = DateTime.Now.AddMonths(1) ' For Expire Cookies Label1.Text = (("Cookie created!<p>" & "Your cookie contains:<font color=red>") + Request.Cookies("MyCookie")("Data") & "<br>") + Request.Cookies("MyCookie") ("Time") & "</font>" End Sub Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click If Request.Cookies("MyCookie") Is Nothing Then Label1.Text = "There is no cookie:" Else Label1.Text = (("Your cookie contains:" & "<font color=red>") + Request.Cookies("MyCookie")("Data") & "<br>") + Request.Cookies("MyCookie") ("Time") & "</font>" End If End Sub End Class

Query String In ASP.NET


Query string is used to Pass the values or information form one page to another page. The query string is a holdover from the ASP days of web programming. You will see this a lot when you are surfing around the internet. Basically, it is passing information to the next page with the URL .You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a simple but limited way of maintaining some state information.

The advantages of using query strings are


No server resources required. The query string is contained in the HTTP request for a specific URL. Broad support. Almost all browsers and client devices support passing values in a query string it is very easy

The disadvantages of using query strings are


Security. The information in the query string is directly visible to the user via the browser user interface. The query values are exposed to the Internet via the URL so in some cases security may be an issue. Limited capacity. Most browsers and client devices impose a 255-character limit on URL length

.VB CODE Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

Response.Redirect("Default.aspx?Name=" & Convert.ToString(Me.txtName.Text) & "&LastName=" & Convert.ToString(Me.txtLastName.Text)) End Sub Our first code part builds a query string for your application and send contents of your textboxes to second page. Now how to retrieve this values from second page. Put this code to second page page_load. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Me.txtBox1.Text = Request.QueryString("Name") Me.txtBox2.Text = Request.QueryString("LastName") End Sub

Server Side State Management


When users visit Web sites it becomes necessary to maintain session related and controls related information. In an HTTP exchange between a browser and a remote host, session related information which identifies state, such as a unique session ID, information about the user's preferences or authorization level is preserved. Note that sessions are maintained in the data being exchanged. State Management is the process by which we maintain session related information and additional information about the controls and its state. The necessity of state management arises when multiple users request for the same or different Web Pages of a Web Site. State management can be accomplished using Client Side options or the Server side options. Session State: Its nothing but defined as a period of time shared between the web application and user. Every user has individual session. Items/Objects can be placed into the Session which would only define these object for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table. Each user would represent a different key node in the hash identifying unique values. The Session variables will be clear by the application which can clear it, as well as through the timeout property in the web config file. Usually the timeout is 20 minutes by default. ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary. Session Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables .The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection.

Example: 'Storing informaton in session state Session("username") = "Ashish" 'Retrieving information from session state Dim str As String = Session("username") Application State: Application State is used to store information which is shared among users of the ASP.Net web application. Application state is stored in the memory of the windows process which is processing user requests on the web server. Application state is useful in storing small amount of often-used data. If application state is used for such data instead of frequent trips to database, then it increases the response time/performance of the web application. In ASP.Net, application state is an instance of HttpApplicationState class and it exposes keyvalue pairs to store information. Its instance is automatically created when a first request is made to web application by any user and same state object is being shared across all subsequent users. Application state can be used in similar manner as session state but it should be noted that many user might be accessing application state simultaneously so any call to application state object needs to be thread safe. This can be easily achieved in ASP.Net by using lock keyword on the statements which are accessing application state object. This lock keyword places a mutually exclusive lock on the statements and only allows a single thread to access the application state at a time. Code Sample 'Stroing information in application state SyncLock Me Application("username") = "william" End SyncLock 'Retrieving value from application state SyncLock Me Dim str As String = Application("username").ToString() End SyncLock

Master Page
Introduction Of Master Page Microsoft ASP.NET 2.0 introduces a new feature .Master Pages. that permits you to define common user interface (UI) elements and common structure in a template that can be applied to multiple content pages in a Web application. Standard elements are, for example, navigational menus, logos, and other stock graphical elements. This allows you to have a common appearance and functionality across your Web site, avoids duplication of code, and makes the site easier to maintain. If the content pages are based on the master page, all the elements defined in the master page would automatically be defined in the content pages.

The page layout for Master Pages is easy to create, simple to maintain, and simple to assign to a Web application. The Master page provides a single point of reference for all pages to display standardized Web content. Master pages are completely transparent to end users and permit developers to create Web sites where pages share a common layout. Defining a Master page is similar to defining a normal page, but saving a Master page is different from saving a normal page. You must save the Master pages by using the .master file extension. How to Add Master Page in Your Application Adding a master page to your web application is straight forward. Just right click on the project and select "Add New Item" and than select "Master Page". This will add the master page to your project. The master page already has the content place holder control which is used to hold and display your contents. Let's delete that content placeholder and add it by our self. In this case we will create two content place holders. One will be on the left and other one on the right .After you insert the content placeholder control inside your table your master page will look something like this:

Using the master page in your aspx pages Just add a new aspx page and name it as "first .aspx". Now you want to use the Sample1.master file in your aspx page. Just go to the html view of your page and add a Master Page File attribute in the page directive and delete all the other html that is written in the aspx page. The Master Page File attribute denotes that the Page is inheriting from the master page. <%@ Page Master Page File="~/Sample1.master" %>

Gridview in ASP.NET
The GridView control displays data as a table and provides the capability to sort columns, page through data, and edit or delete a single record. the GridView control offers improvements such as the ability to define multiple primary key fields, improved user interface customization using bound fields and templates, and a new model for handling or canceling events.

Displays the values of a data source in a table where each column represents a field and each row represents a record. The GridView control enables you to select, sort, and edit these items. Namespace: System.Web.UI.WebControls . Assembly: System.Web (in System.Web.dll) .

GridView Control Features


Enhanced data source binding capabilities (Direct interaction with Data Source with any writing any ADO.NET code) Built-in support for sorting and paging functionalities Improved Design time features(Smart Panel Tag) Customized pager user interface with PagerTemplate property. Additional Column types(ImageField). New Event model with support for pre event and post event operations

Difference between Datagrid,DataList and Data Repeater


Datagrid has paging while Datalist doesnt. Datalist has a property called repeat. Direction = vertical/horizontal. (This is of great help in designing layouts). This is not there in Datagrid. A repeater is used when more intimate control over html generation is required. When only checkboxes/radiobuttons are repeatedly served then a checkboxlist or radio button list are used as they involve fewer overheads than a Datagrid.

Design of Gridview:

.VB Code

Imports System.Data Imports System.Data.OleDb Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim con As OleDbConnection Dim da As OleDbDataAdapter Dim conn As String = System.Configuration.ConfigurationManager.AppSettings("x").ToString() con = New OleDbConnection(conn) da = New OleDbDataAdapter("select purchase1,tax,issue_date from purchase", con) Dim ds As New DataSet() da.Fill(ds, "purchase") GridView1.DataSource = ds.Tables("purchase") GridView1.DataBind() End Sub End Class .ASPX Code <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 100%; } </style> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Height="341px" onselectedindexchanged="GridView1_SelectedIndexChanged" Width="192px"> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> </asp:GridView>

<table class="style1"> <tr> <td> <marquee direction="up" behavior="scroll" onmouseover="this.stop()" onmouseout="this.start()" scrollamount="2" style="width: 383px"> <a href="#">Retail Express Distribution</a><br /><br /> <a href="#">Global Express Consolidation Service</a><br /><br /> <a href="#">Import Express </a><br /><br /> <a href="#">Collect charges and cash on delivery</a><br /> <br /></marquee>&nbsp;</td> <td> &nbsp;</td> </tr> <tr> <td> &nbsp;</td> <td> &nbsp;</td> </tr> </table> </div> </form> </body> </html>

How to EDIT/UPDATE/CANCEL/DELETE in Gridview


Introduction This article explains the methods of binding Asp.Net GridView control with simple DataSet or DataTable, and also explains the methods like Insert, Edit, Update and Delete function in the GridView control. Design of Gridview

Simple DataBind in Gridview Public Sub bindgrid() Dim con As OleDbConnection Dim da As OleDbDataAdapter con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\invent.mdb") da = New OleDbDataAdapter("select item_id, Item,tax from purchase", con) Dim ds As New DataSet() da.Fill(ds, "purchase") GridView1.DataSource = ds.Tables("purchase") GridView1.DataBind() End Sub

How to Call bindgrid Method Public Sub bindgrid() Dim con As OleDbConnection Dim da As OleDbDataAdapter con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\invent.mdb") da = New OleDbDataAdapter("select item_id, Item,tax from purchase", con) Dim ds As New DataSet() da.Fill(ds, "purchase") GridView1.DataSource = ds.Tables("purchase")

End Sub

GridView1.DataBind()

Simple Code For Edit Update And Delete In Gridview Design of EDIT Gridview

How to Edit Gridview


Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing GridView1.EditIndex = e.NewEditIndex bindgrid() End Sub

Design of Update in Gridview

How to Update Gridview


This event will update information in database. Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating Dim UserID As String = GridView1.DataKeys(e.RowIndex).Value.ToString() Dim l As String = DirectCast(GridView1.Rows(e.RowIndex).Cells(1).Controls(0), TextBox).Text Dim k As String = DirectCast(GridView1.Rows(e.RowIndex).Cells(2).Controls(0), TextBox).Text Dim can As New OleDbConnection("provider=microsoft.jet.oledb.4.0; Data source=D:\invent.mdb") can.Open() Dim com1 As New OleDbCommand("update purchase set purchase1='" & l & "',tax='" & k & "' where item_id='" & UserID & "'", can) com1.ExecuteNonQuery() can.Close() 'to go back to the previous position GridView1.EditIndex = -1 ' // fetch and rebind the data. bindgrid() End Sub

Note-- item_id must be primary key And right click on gridview go to property datakey names=item_id(primary key) How to Delete Gridview Design of Delete Row from Gridview

How to Delete Particular Row From Gridview


This event shows how to delete a row from datebase Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting Dim UserID As String = GridView1.DataKeys(e.RowIndex).Value.ToString() Dim can As New OleDbConnection("provider=microsoft.jet.oledb.4.0; Data source=D:\invent.mdb") can.Open() Dim com1 As New OleDbCommand("delete from purchase where item_id ='" & UserID & "'", can) com1.ExecuteNonQuery() can.Close() 'to go back to the previous position GridView1.EditIndex = -1 ' // fetch and rebind the data. bindgrid() End Sub

How to cancel editable mode.


Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit GridView1.EditIndex = -1 bindgrid() End Sub

Simple Select, Edit, Update and Delete in Asp.Net GridView


Design Of Gridview

.ASPX CODE

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/ DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" DataKeyNames="item_id" onrowcancelingedit="GridView1_RowCancelingEdit" onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" onselectedindexchanged="GridView1_SelectedIndexChanged"> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <Columns> <asp:BoundField DataField="item_id" HeaderText="ITEM" /> <asp:BoundField DataField="purchase1" HeaderText="name" /> <asp:BoundField DataField="tax" HeaderText="tax" /> <asp:CommandField ShowEditButton="True" /> <asp:CommandField ShowSelectButton="True" /> <asp:CommandField ShowDeleteButton="True" /> </Columns> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BorderColor="#FF99FF" /> </asp:GridView> </div> </form> </body> </html>

.VB CODE Imports System.Data Imports System.Data.OleDb Partial Class _Default Inherits System.Web.UI.Page Public Sub bindgrid()

Dim con As OleDbConnection Dim da As OleDbDataAdapter con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\invent.mdb") da = New OleDbDataAdapter("select item_id, purchase1,tax from purchase", con) Dim ds As New DataSet() da.Fill(ds, "purchase") GridView1.DataSource = ds.Tables("purchase") GridView1.DataBind() End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then bindgrid() End If End Sub Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing GridView1.EditIndex = e.NewEditIndex bindgrid() End Sub Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating Dim UserID As String = GridView1.DataKeys(e.RowIndex).Value.ToString() Dim l As String = DirectCast(GridView1.Rows(e.RowIndex).Cells(1).Controls(0), TextBox).Text Dim k As String = DirectCast(GridView1.Rows(e.RowIndex).Cells(2).Controls(0), TextBox).Text Dim can As New OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\invent.mdb") can.Open() Dim com1 As New OleDbCommand("update purchase set purchase1='" & l & "',tax='" & k & "' where item_id='" & UserID & "'", can) com1.ExecuteNonQuery() can.Close() 'to go back to the previous position GridView1.EditIndex = -1 ' // fetch and rebind the data. bindgrid() End Sub Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit GridView1.EditIndex = -1 bindgrid() End Sub Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting Dim UserID As String = GridView1.DataKeys(e.RowIndex).Value.ToString() Dim can As New OleDbConnection("provider=microsoft.jet.oledb.4.0;Datasource=D:\invent.mdb") can.Open()

Dim com1 As New OleDbCommand("delete from purchase where item_id ='" & UserID & "'", can) com1.ExecuteNonQuery() can.Close() 'to go back to the previous position GridView1.EditIndex = -1 ' // fetch and rebind the data. bindgrid() End Sub End Class

Validation Control In ASP.NET


Introduction ASP.NET validation controls provide an easy-to-use but powerful mechanism of ensuring that data is entered correctly on the forms. There are 6 validation controls included in the ASP.NET 2.0 and ASP.NET 3.5 versions. ASP.NET validation controls also provide two ways of validation: Server-side or Client-side. The nice thing about these Validation controls is that it will perform client-side validation when it detects the browser is able (unless clientside validation has been disabled). Thus reducing roundtrips. And it will perform server-side where necessary. This client-side/server-side detection and validation is done without extra work by the developer! In ASP.NET, there are five(6) Validation controls included. They are: Validation Server Control CompareValidator CustomValidator RangeValidator RegularExpressionValidator RequiredFieldValidator ValidationSummary Description Compares the value of one input control to the value of another input control or to a fixed value Allows you to write a method to handle the validation of the value entered Checks that the user enters a value that falls between two values Ensures that the value of an input control matches a specified pattern Makes an input control a required field Displays a report of all validation errors occurred in a Web page

How to use Validation Control IN Website: Create a new website project and you have an Empty default.aspx page. In your Solution Explorer double click it and go to its design view. Look for your toolbar on the left hand side of your window. In the Toolbar look for the Validation Section as depicted below

These controls are used to validate the user input provided at the standard controls. Note: If the validation control returns false then the data will not be submitted to the server. A single validation control can validate a single standard control. A single standard control can be binded with any no. of validation controls. Validation scripts should not be altered from ASP. Net 2.0 onwards. If any modifications are performed on the scripts then all the ASP.Net websites which uses validation controls will not function properly. Validation controls can be grouped together from ASP. Net 2.0 onwards

Difference Between Server side Control And Client Side Control 1. Client side validation is processed the client side before submitting the form. The advantage of using the client side validation is it reduces the network traffic since the validation is processed in the client machine itself. 2. Server side validation is processed in the server. Some data cannot be validated in the client side and it has to be validated in the server side. E.g. Date between the two dates in the database. 3. Client-side is faster than server-side as the networking time from client to server is saved. 4. server-side is done on the server. Then the server converts the data into an html page and sends to the browser. 5. server-side is more secure as the user cannot see the code even he does a viewsource.

6. The disadvantage of javascript validation is that users can have javascript turned off and therefore can submit invalid data. 7. The difference is that the javascript validation is done on the client side (if the user's browser supports it, so never depend on javascript alone), before the page is submitted to the server. The advantage is that the user gets immediate feedback and does not need to wait for the page to reload. It also reduces server load.

Required FieldValidator control


It is used to verify if a value has been provided for a control or not. As the name suggest, this validation control make sure that control mention in Control ToValidate cannot be empty. Common properties for all the validation controls: ControlToValidate ErrorMessage Specifies the name of the control which has to be validated. Specifies the error message to be displayed if the validation control returns false.

Note: If customization or if validation controls has to be extended then the Text property for the validation controls should be set. If more than one validation control validates a standard control then it is mandatory that the Display property for all the validation controls should be set as Dynamic. Other than the RequiredFieldValidator control, remaining validation controls will not validate the controls if the value for the control is empty. .aspx Code <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="* Blank are not allowed" SetFocusOnError="True" Display="Dynamic"></asp:RequiredFieldValidator> Output:

CompareValidator control
This Control is used to compare the value or one control to the value of another control or to a fixed value. One catch here is that validation pass if both the fields are empty. To handle that one require to apply Required field validator along with CompareValidator.

<asp:TextBox ID="TextBox1" runat="server" /> <asp:TextBox ID="TextBox2" runat="server" /> <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox2" Display="Dynamic" ValidationGroup="MyGroup" ToolTip=" password not matched No Match" ControlToCompare="TextBox1" > * password not matche pls reenter password</asp:CompareValidator>

ControlToCompare - This take the Id of control with which comparison is being done. Comparison can be made on following data types: Currency, Date, Double, Integer and String Properties ControlToCompare Type Specifies the name of the control which acts like a source control Specifies the data type to be used for validating the input. Default type is string. Specifies the operator to be used for validating the user input. Default is Equal. Grouping the validation controls together: In order to group the validation controls together ValidationGroup property for all the controls which belongs to the group should be set with the same name Output if password are same

Operator

Otherwise

RegularExpressionValidator control
It is used to validate the user input based on the validation expression. Meta characters used to prepare the expression for single digit \d /D \w \s [A-Za-z] [0-9] ^[0-9] Occurrences: It is used to specify the occurrence of the meta characters within the expression. {number} Accepts the input if the length of the expression is equal to the specified number E.g.: \d{5} accepts 5 digits number {Minnumber, } Accepts the input if the length after expression is greater than or equal to the specified Minnumber. E.g: [A-Za-z0-9_]{6, } Accepts a single digit Accepts a single character Accepts any character other than a white space (spacebar) Accepts a space Accepts upper or lower case characters Accepts a numerical value Accepts any characters other than numeric value

{Minnumber, Maxnumber}

Accepts the input if the length of the expression is between the specified range. e.g.: \D{6,8}

Modes: It is used to specify the occurrence of the meta characters within the expression. Mode ? MinOccurrence 0 MaxOccurrence 1

. or * + E.g.: \d{1, } <==> \d+

0 1

Any Any

[ma+am] => accepts madam, Malayalam .ASPX CODE <asp:TextBox ID="TextBox1" runat="server"> </asp:TextBox><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="plese enter email ID" ToolTip="plese Enter email id" ValidationExpression="\w+([-+.']\w+)*@\w+ ([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator> Output:

Custom Validator control


It is used to validate user input based on the user defined functionality. OR Custom validator control is used to capture the validation that cannot be handled by the validator controls provided by ASP.NET. Here user is at the freedom to define his own custom method, both Client side and Server side. CustomValidator is the only validator control which has the capability to validate the user input at the client side and also at the server side. Other than the CustomValidator, all the controls will validate the user input at the client side. Property ClientValidationFunction Specifies the JavaScript function name, which provides the definition to validate the user input at the client side.

Event ServerValidate The code written within this event will be used to validate the user input at the server side.

.aspx Code

Custom text:<br /> <asp:TextBox runat="server" id="txtCustom" /> <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" /> <br /><br /> .VB CODE Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate If args.Value.Length = 8 Then args.IsValid = True Else args.IsValid = False End If End Sub ValidateEmptyText is a boolean attribute that if set to true, the input control will be validated even if it is empty. ClientValidationFunction contains name of client validation function. OnServerValidate contains name of server validation function.

Validation Summary control


This control is used to display the list of all the validation error that has occurred on the page. The error message displayed is the one set for the ErrorMessage attribute of the validation control. No error message will be displayed if this attribute is not set. ASP.NET has provided an additional control that complements the validator controls .The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list. The list can be either shown on the web page (as shown in the example above) or with a popup box (by specifying ShowMessageBox="True").. DisplayMode has three options List, BulletList and SingleParagraph ShowMessageBox when set to true will display the error as a alert popup ShowSummary will display the error on the page. By default it is true. .ASPX CODE

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default4.aspx.vb" Inherits="Default4" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/ xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 52%; border-left-style: solid; border-left-width: 1px; border-right: 1px solid #C0C0C0; border-top-style: solid; border-top-width: 1px; border-bottom: 1px solid #C0C0C0; background-color: #008000; } .style2 { color: #FFFFFF; } .style3 { width: 126px; } </style> </head> <body> <form id="form1" runat="server"> <div> <table class="style1"> <tr> <td class="style2" colspan="2"> &nbsp; Regular&nbsp; Expression Validator&nbsp;</td> <tr> <td class="style2"> Email ID</td> <td class="style3"><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td> <td><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="plese enter email ID" ToolTip="plese Enter email id" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator> </td> </tr> <tr> <td class="style2"> Name</td> <td class="style3"> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td> <td> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="Blank not Allowed"

SetFocusOnError="True"></asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style2"> Age</td> <td class="style3"> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> </td> <td> <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox3" ErrorMessage="Age should be Between !8 to 35" MaximumValue="35" MinimumValue="18"></asp:RangeValidator> </td> </tr> <tr> <td class="style2"> &nbsp;</td> <td class="style3"> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" Width="123px" /> </td> <td> <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" ShowSummary="False" /> </td> </tr> <tr> <td class="style2"> &nbsp;</td> <td class="style3"> &nbsp;</td> <td> </tr> </table> </div> </form> </body> </html> Output:: &nbsp;</td>

Label Control in ASP.NET


It is used to provide the static information on the webform. Common properties for all the server side controls Id Used to specify the unique identifier for the control placed on the webform..

runat="Server" all control run on sever Text It is used to set or get the value from the server side control..

The id attribute is used to uniquely identify the <asp:label> control so you can refer to it in your ASP.NET code. The runat="server" attribute tells the server to process the control and generate HTML code to be sent to the client. The class hierarchy for this control is as follows 1. 2. 3. 4. Object Control Web Control Label

Syntax of Label Control <asp: Label ID="Label1" runat="server" Text="This is a label control"> </asp: Label>

Simple Example of Lebel Control Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Label1.Text = "Hi I AM Label control" End Sub Click On Button

How To Write Line Break In ASP.NET Label Control To write text in lines in standard ASP.NET label control you need to use HTML tag <br />. This is example label control that contains text in Four Lines lines: <asp:Label ID="Label1" runat="server" Text="This is Aditya<br />This is kamal<br /> This is Anil<br/> This is Ashish"> </asp:Label>

TextBox Control in ASP.NET


TextBox Control is used for user to enter the input like any string eg., Name, Password , number etc., Asp.NET TextBox itself is a class which is present under System.Web.UI.WebControls namespace. It is used to accept SingleLine, MultiLine or Password characters as the input. Syntax Of Textbox <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> Properties Property AutoCompleteType Description Specifies the AutoComplete behavior of a TextBox A Boolean value that specifies whether the control is automatically posted back to the server when the contents change or not. Default is false Specifies if a page is validated when a Postback occurs The width of the textbox

AutoPostBack

CausesValidation Columns

MaxLength ReadOnly Rows runat TagKey Text TextMode ValidationGroup Wrap

The maximum number of characters allowed in the textbox Specifies whether or not the text in the text box can be changed The height of the textbox (only used if TextMode="Multiline") Specifies that the control is a server control. Must be set to "server"

The contents of the textbox Specifies the behavior mode of a TextBox control (SingleLine, MultiLine or Password) The group of controls that is validated when a Postback occurs A Boolean value that indicates whether the contents of the textbox should wrap or not The name of the function to be executed when the text in the textbox has changed

OnTextChanged

Example .vb CODE Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click ListBox1.Items.Add("Name:" + TextBox3.Text) ListBox1.Items.Add("father Name:" + TextBox4.Text) ListBox1.Items.Add("Course:" + TextBox5.Text) ListBox1.Items.Add("college:" + TextBox6.Text) End Sub Output

Button Control in ASP.NET


Button control is generally used to post the form or fire an event either client side or server side. When it is rendered on the page, it is generally implemented through <input type=submit> HTML tag. However, if UserSubmitBehavior property is set to false then control will render out as <input type=button>. Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented through style properites of <input> tag. You can set its Text property either by setting Text property in the .aspx page or from server side page. (other properties can also be set from both pages)

The Button control is used to display a push button. The push button may be a submit button or a command button. By default, this control is a submit button. A submit button does not have a command name and it posts the page back to the server when it is clicked. It is possible to write an event handler to control the actions performed when the submit button is clicked. A command button has a command name and allows you to create multiple Button controls on a page. It is possible to write an event handler to control the actions performed when the command button is clicked. Properties Properties CausesValidation CommandArgument CommandName OnClientClick PostBackUrl runat Text UseSubmitBehavior ValidationGroup Example Description Specifies if a page is validated when a button is clicked Specifies additional information about the command to perform Specifies the command associated with the Command event Specifies the name of the function to be executed when a button is clicked Specifies the URL of the page to post to from the current page when a button is clicked Specifies that the control is a server control. Must be set to "server" Specifies the text on a button Specifies whether or not a button uses the browser's submit mechanism or the ASP.NET postback mechanism Specifies the group of controls a button causes validation, when it posts back to the server

.vb Code Protected Sub Button1_Click(ByVal sender As Object,

ByVal e As System.EventArgs) Handles Button1.Click Response.Write("Hi... Friends your College Name is:" + TextBox1.Text) End Sub

Image Button in ASP.NET


ImageButton control is used to display an image that responds to mouse clicks. Specify the image to display in the control by setting the ImageUrl property. Both the Click and Command events are raised when the ImageButton control is clicked. By using the OnClick event handler, you can programmatically determine the coordinates where the image is clicked. You can then code a response based on the values of the coordinates. Note the origin (0, 0) is located at the upper-left corner of the image. You can use the OnCommand event handler to make the ImageButton control behave like a command button. A command name can be associated with the control by using the CommandName property. This allows multiple ImageButton controls to be placed on the same Web page. The value of the CommandName property can then be programmatically identified in the OnCommand event handler to determine the appropriate action to perform when each ImageButton control is clicked. The CommandArgument property can also be used to pass additional information about the command, such as specifying ascending order. Property Description Specifies if a page is validated when an CausesValidation ImageButton control is clicked Additional information about the command to CommandArgument perform The command associated with the Command CommandName event Specifies whether or not the control creates an GenerateEmptyAlternateText empty string as an alternate text The name of the function to be executed when OnClientClick the image is clicked The URL of the page to post to from the current PostBackUrl page when the ImageButton control is clicked Specifies that the control is a server control. ValidationGroup Must be set to "server" The group of controls for which the ImageButton runat control causes validation when it posts back to the server How to Set Image On Button Property

Output

Hyperlink control in ASP.NET


The Hyperlink Web server control is used to create a link to another Web page. The text in the HyperLink control is specified using the Text property. We can also display a image on this control instead of text. Properties: These are the following properties of the Hyperlink control.

Figure 1. Text - The text to be shown for the link. ImageUrl - gets\sets The image to be displayed in the hyperlink. NavigateUrl - The URL to navigate to when the hyperlink is clicked. Target - The target property allows us to set new page/content to be displayed in a new browser window, same window, etc. The values are as follows: _blank: displays the linked content in a new window without frames. _parent: displays the linked content in the immediate frameset parent.

_self: displays the linked content in the frame with focus. _top: displays the linked content in the full window without frames. ToolTip - ToolTip displayed when the mouse is over the control.

Example Design

Right Click on Home

Output When you click On Hyperlink it will show home Page of website

Literal Control in ASP.NET


The Literal Control is similar to the Label Control as they both are used to display static text on a web page. The Literal Control is not inherited from WebControl namespace. The Literal Control doesn't provide substantial functionality but Literal text is programmable. It doesn't add any HTML elements to the web page. This control makes it possible to add HTML code directly in the code designer window without switching to design view and clicking the HTML button to edit the HTML. You cannot apply a style to a literal control. Unlike Label control, there is no property like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. for Literal control. That makes it more powerful, you can even put a pure HTML contents into it.

The Literal control is used to display text; that is, it renders static text on a Web page without adding additional HTML tags. It passes content directly to the client browser unless you use the Mode property to encode the content. Syntax of Literal Control

<asp:Literal ID="LiteralText" runat="server" Text="This is example of Literal"></asp:Literal> Important Properties of Asp.NET Webserver Literal control are given below. You can Set /Get these properties at Design time or at Runtime. Mode - Enumerator - To specify how to render literal control in a web page. Text - Accept String - Commenly Used property to Get/Set the text that you want to render in your webpage There are three Mode enumerator available. These are

1. PassThrough : If you set this property, then the content will not be modified and
rendered as is. For eg., if string contains <hr> tag then its dependent on your browser, of how it handles <hr> tag. 2. Encode : If you set this property then content will be encoded and sent to browser for eg., if your string contains <hr> tag, then your string will be converted to &lt;Hr&gt; and sent to browser. 3. Transform : If you set Mode property to Transform then the string render depends upon the type of the markup. Events available in Asp.Net Web server Literal Control are: Click Init Load PreRender UnLoad The difference between a Label Control and a Literal Control? 1. The main difference is, you can apply style to a Label control where as you can not apply styles in a literal control. 2. Label control renders as span tag in a webpage while Literal Control only shows the text without any tag associated to it. 3. Literal control does not maintain its viewstate. 4. It's always a good practice to use literal control when you want to display a plain text in your web page. ASP.NET Literal itself is a class which is present under System.Web.UI namespace.

.aspx code: <asp:Literal ID="Literal1" runat="server"></asp:Literal> <asp:Literal ID="Literal2" runat="server"></asp:Literal> <asp:Literal ID="Literal3" runat="server"></asp:Literal> .vb Code:

Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click Literal1.Mode = LiteralMode.Encode Literal1.Mode = LiteralMode.PassThrough Literal1.Mode = LiteralMode.Transform Literal1.Text = "<font size=4 color=red>Literal1 with Encode property example </font><script>alert(""Literal with Encode property"");</script></br></br>" Literal2.Text = "<font size=4 color=green>Literal2 with PassThrough property example </font><script>alert(""Literal with PassThrough property"");</script></br></br>" Literal3.Text = "<font size=4 color=blue>Literal3 with Encode Transform example </font><script>alert(""Literal with Transform property"");</script></br></br>" End Sub Output:

ASP.NET LinkButton Control


Link Button Control is similar to Button Control. Everything is similar in properties and events,except that user can see it as a Link. Syntax Of Link Button <asp:LinkButton ID="LinkButton1" runat="server" >Home</asp:LinkButton> Important Properties

AccessKey: specify a key that navigates to the Button control. CommandArgument: specify a command argument that is passed to the Command event. CommandName: specify a command name that is passed to the Command event. Enabled: disable the LinkButton control. OnClientClick: specify a client-side script that executes when the LinkButton is clicked. PostBackUrl: post a form to a particular page. TabIndex: specify the tab order of the LinkButton control. Text: label the LinkButton control. Focus: set the initial form focus to the LinkButton control.

LinKButton Event Event Click Command Example .vb Code Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click Label1.Text = "This is my Home Page" End Sub Protected Sub LinkButton2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton2.Click Label1.Text = "My Company name R4r TechSoft Solution " End Sub Protected Sub LinkButton3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton3.Click Label1.Text = "My Name is Rituraj Tyagi And My Contact No... 9717009112" End Sub Description occurs when the LinkButton control is clicked by the user. occurs when the LinkButton control is clicked and passes its associated CommandName and CommandArgument to the server side event handler.

DropDownList in ASP .NET


A DropDownList is also commonly known as combo box. It can contain multiple data members, but unlike a normal list box the users can choose only one value from this control. Though the functionality of this DropDownList is much like a Single Row Select List Box, a DropDownList can save a lot of GUI space as it is rendered on a Single line and is expanded only when the user clicks on the Control. This DropDownList is provided as a Server Control in ASP .Net like many other controls. This DropDownList can be used to add data manually or even for dynamic binding with data base. A simple declaration for DropDownList can be done as below. <asp:DropDownList ID="DropDownList1" runat="server" Height="47px" Width="73px"></asp:DropDownList> Properties Of DropDownList Control Properties BorderColor BorderStyle BorderWidth SelectedIndex AppendDataBoundItems Discription enables to get or set the border color of the web server control. [Not Applicable] enables to get or set the border style of the control. [Not Applicable] enables to get or set the border width for the control. [Not Applicable] enables to get or set an Integer value to specify the zero-based index for the currently selected list item. enables to get or set a Boolean value to indicate whether to clear the list items before binding the data to the control. enables to get or set a Boolean value that indicates whether to postback the web page when list item of DropDownList control is clicked. enables to get or set the name of the data source field that provides the text for the list items. enables to get or set the string formatting to control the text of each list item that is to be displayed. enables to get or set the name of the data source field that provides the value for the list items. enables to manage the list items of the DropDownList control.

AutoPostBack DataTextField DataTextFormatString DataValueField Items

SelectedItem SelectedValue Text ValidationGroup

DataMember

DataSourceID

DataSourceObject DataSource CausesValidation

enables to get the currently selected list item in DropDownList control. enables to get the value property of selected list item that returns ListItem object enables to get or set the text for the control. enables to get or set the name of the group of controls to which it belongs to and causes validation when posts back to the server. enables to get or set the name of the list of data that the data-bound control binds to. The list of data items may have more than one data members. enables to get or set the ID of the DataSource control from which the data-bound control retrieves its list of data items. enables to get an object that implements the IDataSource interface and provides the access to the data items. enables to get or set the object from which the databound control retrieves its list of data items. enables to get or set a Boolean value to indicate whether to perform the validation when any list item of the control is clicked.

Events SelectedIndexChanged: Occurs when selected item of list control changes between postbacks to the server. TextChanged: Occurs when Text and SelectedValue properties change between postbacks to the server. Example:

.vb Code:

Partial Class Default4 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then DropDownList1.Items.Add("pototo") DropDownList1.Items.Add("Tamato") DropDownList1.Items.Add("brinjal") DropDownList1.Items.Add("Lime") DropDownList1.Items.Add("Pea") DropDownList2.Items.Add("Jeans") DropDownList2.Items.Add("Shirt") DropDownList2.Items.Add("Cap") DropDownList2.Items.Add("Blaser") DropDownList2.Items.Add("Tie") DropDownList3.Items.Add("Lather") DropDownList3.Items.Add("Canvas") DropDownList3.Items.Add("Sports") DropDownList3.Items.Add("Sandle") DropDownList3.Items.Add("Sleeper") DropDownList4.Items.Add("Fan") DropDownList4.Items.Add("TybeLight") DropDownList4.Items.Add("Plug") DropDownList4.Items.Add("Holder") DropDownList4.Items.Add("Wire") End If End Sub Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged ListBox1.Items.Add("Vegitables:" + DropDownList1.SelectedItem.Text) End Sub Protected Sub DropDownList2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList2.SelectedIndexChanged ListBox1.Items.Add("Cloths:" + DropDownList2.SelectedItem.Text) End Sub Protected Sub DropDownList3_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList3.SelectedIndexChanged ListBox1.Items.Add("Showes:" + DropDownList3.SelectedItem.Text) End Sub Protected Sub DropDownList4_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList4.SelectedIndexChanged ListBox1.Items.Add("Electronics:" + DropDownList4.SelectedItem.Text) End Sub End Class

Das könnte Ihnen auch gefallen