Thursday, June 24, 2010

Important .Net Interview Question


Difference between Difference between Microsoft.net Framework 2.0 and 3.5
1.Visual Studio 2008 has offered a great new experience to target multiple frameworks in one place
2. we can merge two or more assemblies into one .net assembly with the new .net merge tool.
3. The new controls introduced in Asp.net are LinqDataSource, ListView and DataPager.
4. One of the major advancement in Framework 3.5 is LINQ, though we can use LINQ in Framework 2 as well after installing a separate executable, which is now fully supported automatically. Linq allows us to use and interact with data as an object. Now no matter what type of data we have we can play with them using Linq easily.
5. There is added extended support for JSON, there is design time code validation and checks, also, new design time editor support is provided.

  New in .NET framework 2.0

It brings a lot of evolution in class of the framework and refactor control including the support of

  • Generics
  • Anonymous methods
  • Partial class
  • Nullable type
  • The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more
  • Full 64-bit support for both the x64 and the IA64 hardware platforms
  • New personalization features for ASP.NET, such as support for themes, skins and webparts.
  • .NET Micro Framework 

New in .NET framework 3.0
Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides
  • Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services. 
  • Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies. 
  • Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.  
  • Windows CardSpace, formerly called InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website

New in .NET framework 3.5
It implement Linq evolution in language. So we have the following evolution in class:

  • Linq for SQL, XML, Dataset, Object
  • Addin system
  • p2p base class
  • Active directory
  • ASP.NET Ajax
  • Anonymous types with static type inference
  • Paging support for ADO.NET
  • ADO.NET synchronization API to synchronize local caches and server side datastores
  • Asynchronous network I/O API .
  • Support for HTTP pipelining and syndication feeds.
  • New System.CodeDom namespace.

Everyone who writes code
  Describe the difference between a Thread and a Process?
A process is a execution unit in it's own address space, a thread can't run on it's own - a process has to 'fork' one. For example, IIS runs as a process but as http requests come in, it spawns threads to handle each request.
  What is a Windows Service and how does its lifecycle differ from a "standard" EXE?
windows service runs with it's own credential(different from the logged on user's credentials). It doesn't stop if the logged on user logs off.
What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
What is the difference between an EXE and a DLL?
An exe runs in it's own address space, Dll gets loaded into the 'hosting' process address space or a shared address space.
  What is strong-typing versus weak-typing? Which is preferred? Why?
Strong typing provides greater type safety. You might have specially heard it about DataSets being strongly typed, where instead of referring columns as datacolumns(index).value, you create an XML schema from which you make a dataset derived class. Strong typing is preferred as there remains no type ambiguity. Another example is, turning on Option strict in VB, where you have to do explicit type casts.Instead of running into situation where you get a type that you did not expect and try performing an operation on it, you go for strong typing so that such errors are caught during compile time itself.
 Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.
  What is a PID? How is it useful when troubleshooting a system?
PID is process id. Have used this mostly to kill processes in Unix.
One. Only one can capture the incoming packet.
  What is the GAC? What problem does it solve?
GAC=Global Assembly Cache, solves dll versioning(hell) problem. It's interesting to know how it solves the problem, each assembly is uniquely identified by 4 'things' major version number,minor version, build and revision numbers.For each differing version, the GAC silently creates a subfolder based on a hash of these and places the assembly in it.From a user perspective it seems as if, we are moving the same file in one directory and it doesn't ask if it should overwrite the file !
Mid-Level .NET Developer
  Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

Interface-Oriented


Interface-oriented programming is a contract-based approach. Nether side of the interface cares how the other does its work, only that the two sides can communicate via an agreed-upon contract. WSDL-based web services are the prime example of this.


Object-Oriented


Object-Oriented programming is based on abstraction, encapsulation (data hiding), polymorphism and inheritance. Classes implement these concepts to build objects controlling or implementing a system.


Abstraction allows loose coupling between components by providing a layer between objects so that one object isn't concerned with how the other implements its business rules. (Interfaces, layers) Great stuff when you want to isolate parts of the system so they can be swapped out without killing the rest of the sytsem.


Encapsulation allows abstraction to work by hiding details of a class's implementation from calling classes. (Public vs. private fields)


Inheritance enables base (parent) classes to have common functionality defined in it and passed down to child classes. A Shape class might have a field for color which is inherited by child classes of Square or Circle type.


Polymorphism enables implementation of same-named public fields, allowing different classes to perform different actions on the same call - rendering a Square or Circle object differently in a graphic program, even though they might both be subclassed from a base Shape class. (Overriding)


Aspect-Oriented


Aspect-oriented programming looks at how many components or pieces of a system might need to interact. The intersections of these pieces are what are important in AOP. \"Crosscutting\" is a slice across several units, all of which interact during some operation. The article Discussing aspects of AOP in Communications of the ACM, Volume 44, Number 10 (2001) shows an example of a drawing editor with point and line elements. If the drawing is moved, both point and line elements need to update. A crosscut hits these elements for this event. Other examples might include logging or exception handling which hit several different layers in a system. (Viji Sarathy, Aspect Orienting .NET Components )


  Describe what an Interface is and how it’s different from a Class.
  An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
  An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesnt support multiple inheritance, interfaces are used to implement multiple inheritance.
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants
No fields can be defined in interfaces
An abstract class can have fields and constrants defined

  What is Reflection?
  What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
  Are the type system represented by XmlSchema and the CLS isomorphic?
  Conceptually, what is the difference between early-binding and late-binding?
  Is using Assembly.Load a static reference or dynamic reference?
  When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?
  What is an Asssembly Qualified Name? Is it a filename? How is it different?
  Is this valid? Assembly.Load("foo.dll");
  How is a strongly-named assembly different from one that isn’t strongly-named?
  Can DateTimes be null?
  What is the JIT? What is NGEN? What are limitations and benefits of each?
  How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?
  What is the difference between Finalize() and Dispose()?
  How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
  What does this useful command line do? tasklist /m "mscor*"
  What is the difference between in-proc and out-of-proc?
  What technology enables out-of-proc communication in .NET?
  When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?
Senior Developers/Architects
  •   What’s wrong with a line like this? DateTime.Parse(myString);
  •   What are PDBs? Where must they be located for debugging to work?
  •   What is cyclomatic complexity and why is it important?
  •   Write a standard lock() plus “double check” to create a critical section around a variable access.
  •   What is FullTrust? Do GAC’ed assemblies have FullTrust?
  •   What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
  •   What does this do? gacutil /l | find /i "Corillian"
  •   What does this do? sn -t foo.dll
  •   What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
  •   Contrast OOP and SOA. What are tenets of each?
  •   How does the XmlSerializer work? What ACL permissions does a process using it require?
  •   Why is catch(Exception) almost always a bad idea?
  •   What is the difference between Debug.Write and Trace.Write? When should each be used?
  •   What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
  •   Does JITting occur per-assembly or per-method? How does this affect the working set?
  •   Contrast the use of an abstract base class against an interface?
  •   What is the difference between a.Equals(b) and a == b?
  •   In the context of a comparison, what is object identity versus object equivalence?
  •   How would one do a deep copy in .NET?
  •   Explain current thinking around IClonable.
  •   What is boxing?
  •   Is string a value type or a reference type?
  •   What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?
  •   Why are out parameters a bad idea in .NET? Are they?
  Can attributes be placed on specific parameters to a method? Why is this useful?
C# Component Developers
Ø  Juxtapose the use of override with new. What is shadowing?
Ø  Explain the use of virtual, sealed, override, and abstract.
Ø  Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d
Ø  Explain the differences between public, protected, private and internal.
Ø  What benefit do you get from using a Primary Interop Assembly (PIA)?
Ø  By what mechanism does NUnit know what methods to test?
Ø  What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}
Ø  What is the difference between typeof(foo) and myFoo.GetType()?
Ø  Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?
Ø  What is this? Can this be used within a static method?
ASP.NET (UI) Developers
Ø  Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick.
Ø  What is a PostBack?
Ø  What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?
Ø  What is the <machinekey> element and what two ASP.NET technologies is it used for?
Ø  What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?
Ø  What is Web Gardening? How would using it affect a design?
Ø  Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design?
Ø  Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET?
Ø  Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad?
Ø  Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page.
Ø  What kinds of events can an HttpModule subscribe to? What influence can they have on an implementation? What can be done without recompiling the ASP.NET Application?
Ø  Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET.
Ø  Explain how cookies work. Give an example of Cookie abuse.
Ø  Explain the importance of HttpRequest.ValidateInput()?
Ø  What kind of data is passed via HTTP Headers?
Ø  Juxtapose the HTTP verbs GET and POST. What is HEAD?
Ø  Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client.
Ø  How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?
Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.
Ø  How does VaryByCustom work?
Ø  How would one implement ASP.NET HTML output caching, caching outgoing versions of pages generated via all values of q= except where q=5 (as in http://localhost/page.aspx?q=5)?
Ø  Developers using XML
Ø  What is the purpose of XML Namespaces?
Ø  When is the DOM appropriate for use? When is it not? Are there size limitations?
Ø  What is the WS-I Basic Profile and why is it important?
Ø  Write a small XML document that uses a default namespace and a qualified (prefixed) namespace. Include elements from both namespace.
Ø  What is the one fundamental difference between Elements and Attributes?
Ø  What is the difference between Well-Formed XML and Valid XML?
Ø  How would you validate XML using .NET?
Ø  Why is this almost always a bad idea? When is it a good idea? myXmlDocument.SelectNodes("//mynode");
Ø  Describe the difference between pull-style parsers (XmlReader) and eventing-readers (Sax)
Ø  What is the difference between XPathDocument and XmlDocument? Describe situations where one should be used over the other.
Ø  What is the difference between an XML "Fragment" and an XML "Document."
Ø  What does it meant to say “the canonical” form of XML?
Ø  Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve?
Ø  Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?
Ø  Does System.Xml support DTDs? How?
Ø  Can any XML Schema be represented as an object graph? Vice versa?
*        
C# winform Question

What are windows form applications?

Windows form applications are standard applications for Windows operating system having a user interface. A windows form application usually has one or more forms containing menus and other user interface controls like buttons, text boxes, tree view, etc. Windows form applications are like any other application on Windows except that it has its own Graphical User Interface (GUI). Common examples of windows form applications include Microsoft Word, Adobe Photoshop and Winamp. Windows form applications are event based, i.e., they perform certain operations on user action. For example, Microsoft Word saves the document into disk file only when you ask the application to do so (selecting File > Save).

How are the Windows form applications different from the Console Applications?

Windows applications are facilitated with the Windows standard user interface controls (like button, text box, list box, picture box and etc) and the standard events of Windows operating system. On the other hand, the Console Application can only take user input and output from/to the Console, command or a shell window. Windows form applications are more responsive and may use a lot of features like shortcut and icons. On the other hand, console applications are light weight and are used for testing and background service type applications. Several Java based web servers are implemented on Windows using Console application.

How is the Windows form application development supported in .NET?

Most of the library classes for Windows form application development are present in .NET framework’s System.Windows.Forms namespace. All the forms in .Net are represented by sub-classes of System.Windows.Forms.Form class. To make a form, we need to inherit our form class from the System.Windows.Forms.Form class.

A form may contain various user interface (UI) controls. All the controls, in .NET, are represented by subclasses of System.Windows.Forms.Control class. Each form has a collection (named ‘Controls’) to store the constituent controls of the form. In fact, a form itself is a special type of control called Container Control, i.e., the Form class itself is derived from the ContainerControl class which is a subclass of the Control class. A container control, as the name suggests, may contain other controls. Other examples of the Container control include Panel and Tab Control.

Each control, and thus form, exposes a number of events that can be triggered on certain user action or application behavior. For example, a button raises Click event whenever it is clicked and the text box raises the TextChanged event whenever its text is changed. The application developer can write even handler to catch these events and perform corresponding action. Beside these, a form also has certain set of events called the form life cycle events. These events are triggered during the life cycle of form to indicate the current state of the form.

What support does the Visual Studio.NET provide for the development of .NET win form applications?

Visual Studio.NET provides an enormous support for the development of Win Form applications. The key features of Visual Studio.NET IDE include:
  • The form designer allows you to design the User Interface (UI) of the applications by simple drag and drop of the controls.
  • The Properties window allows you to set different properties for form and a number of windows controls
  • The Intellisense (help completing the syntax as you place dot (.) with objects, enumeration and namespace and when you create new objects)
  • Project and solution management with solution explorer that helps manage applications consisting of multiple files, which is what usually happens
  • Standard debugger that allows you to debug your program by putting break points for observing run-time behavior of the variables and objects in the program
  • Hot compiler that checks the syntax of your code as you type it and report any errors present
  • Dynamic Help on number of topics using Microsoft Development Network (MSDN) Library
  • Compilation and building applications
  • Execution of your application with/without debugger
  • Deploying your .NET application over the Internet or on CDs

How do I make my first “Hello, WinForm” .NET form application using VS.NET and Visual C#?

C# Version Using Visual Studio.NET to build the “Hello WinForm” Application So we have had a lot of Visual Studio.NET introduction. Now, let’s use Visual Studio.NET IDE to build the “Hello WinForm” application which we created earlier in the lesson.

Creating a new Project First of all, we need to create a new C# Windows Application Project. For this, start Visual Studio.NET and click File -> New -> Project. It will show the following screen

From the above screen, select ‘Visual C# Projects’ in Project types and ‘Windows Application’ in Templates. Write the name of the new project (‘LearningWinForm’ in the above figure) in the text box labeled Name. Select the disk path where you wish to store the project using Browse… Button and click OK. It will show you an empty form in the designer view similar to the figure below

The layout of the form designer screen may be somewhat different from the one shown above. Your toolbox and properties window may be visible and some other windows may not be visible. You can change these settings using View menu as described earlier in the lesson.

Setting various properties of the form You can change the default properties of the form using the Properties window. For this, select (click) the form and select the properties window (If the properties window is not visible in the right hand pan, select View -> Properties Window). Now change the title of the form and the name of the form’s class in the code using Text and Form’s Name property respectively as shown in the following figure.

Adding Controls to the Form Now select the Label control from toolbox and place it on the form and resize it as appropriate. Select (click) the label on the form and from the properties window, set its Text property to “Hello WinForm” and the Name property to ‘lblGreeting’. The name of a control is the name of its corresponding instance in the source code. Now select the Button control from toolbox and place it on the form and resize it appropriately. Select (click) the button and set its Name property as ‘btnExit’ and Text property as ‘Exit’ from the properties window. The form should now look like

Adding Event Handling Now, we need to add the event handling code for the Exit button. For this, simply double click the Exit button in the designer. It will create a new event handler for the Exit button’s Click event and take you to the source code as shown in the following figure

Write the code to close the application (Application.Exit()) in the event handler. The IDE in fact has not only created the event handler but also has registered it with the Exit button’s Click event.

Executing the application That is it! The ‘Hello WinForm’ application is complete. To compile and execute the application, select Build -> Build Solution (or press Ctrl+Shift+B) and then select Debug -> Start Without Debugging (or press Ctrl+F5).

Author’s Note: Unfortunately, my copy of Visual Studio.NET 2001 does not change the name of form (from Form1 to MyForm in our case) in the call to Application.Run() method in the Main() method. I have to explicitly change the Main() method like this
               static void Main() 
               {
                               Application.Run(new MyForm());
               }


If you are also experiencing the same problem with your copy of Visual Studio.NET, make sure to change the name of the form in Main() method also whenever you change its name in the Properties Window in order to avoid the compilation error

This will compile and start the ‘Hello WinForm’ application in a new window as shown below

To close the application, click the Exit button or the close button at the title bar of the window.

The code generated by the Form Designer You can toggle between Form Designer and Code using View -> Designer and View -> Code. After switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.

How do I make my first “Hello, WinForm” .NET form application without VS.NET in Visual C#?

C# Version

Building the “Hello WinForm” Application Let’s now build our first windows application called “Hello WinForm”. The application will present a simple window with “Hello WinForm” greeting at the center. The source code of the program is:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
{
               class Test
               {
                               static void Main()
                               {
                                              Application.Run(new MyWindow());
                               }
               }
               class MyWindow : Form
               {
                               public MyWindow() : base()
                               {
                                              this.Text = "My First Windows Application";
                                              this.Size = new Size(300, 300);
                                              Label lblGreeting = new Label();
                                              lblGreeting.Text = "Hello WinForm";
                                              lblGreeting.Location = new Point(100, 100);
                                              this.Controls.Add(lblGreeting);
                               }
               }
}
Understanding the Code
In the start, we included three namespaces to our application
using System;
using System.Windows.Forms;
using System.Drawing;


The System namespace, as we stated in the first lesson, is the necessary ingredient of all C# applications. In fact, the Application class that we used later in the Main() method is defined in this namespace. The System.Windows.Forms namespaces contains the base classes for windows controls like Form, Label and Button. Finally, including the System.Drawing namespace is necessary as it contains the useful classes related to the drawing of controls. The Size and Point classes used later in the program are actually defined in System.Drawing namespace.

Later, we derived a new class ‘MyWindow’ from the Form class defined in
System.Windows.Forms 
               class MyWindow : Form
               {
               ...
               }


In the constructor of MyWindow, we specified the size and title of the form. The size is defined using the System.Drawing namespace’s Size class. We passed two integers to the constructor of Size to specify the width and the height of the form.
               public MyWindow() : base()
               {
                               this.Text = "My First Windows Application";
                               this.Size = new Size(300, 300);


Next in the constructor, we created a text label and added it to the Controls collection of the Form. A text label is used to write some text on the form. The System.Windows.Forms.Label class is used to create a text label in windows applications. We set the text of the Label using its Text property which is of string type. All the controls contained by a form must be added to its Controls collection; hence we have also added our label to this collection.
               public MyWindow() : base()
               {
                               this.Text = "My First Windows Application";
                               this.Size = new Size(300, 300);
                               Label lblGreeting = new Label();
                               lblGreeting.Text = "Hello WinForm";
                               lblGreeting.Location = new Point(100, 100);
                               this.Controls.Add(lblGreeting);
               }


Finally, we have created a Test class containing the Main() method. In the Main() method, we have instantiated the MyWindow class and passed its reference to the Application.Run() method so it may receive messages from the Windows Operating System.

When we execute the above code, the following screen is presented as output

To close the application, press the close button on the title bar.

Adding Event Handling Let’s now add a button labeled ‘Exit’ to the form. The ‘Exit’ button will close the application when it is clicked. In .NET, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button’s Click event. Following is the code for this modified application
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
{
               class Test
               {
                               static void Main()
                               {
                                              Application.Run(new MyWindow());
                               }
               }
               class MyWindow : Form
               {
                               public MyWindow() : base()
                               {
                                              // Form
                                              this.Text = "My First Windows Application";
                                              this.Size = new Size(300, 300);
                                              this.StartPosition = FormStartPosition.CenterScreen;
                                              // Label
                                              Label lblGreeting = new Label();
                                              lblGreeting.Text = "Hello WinForm";
                                              lblGreeting.Location = new Point(100, 100);
                                              // Button
                                              Button btnExit = new Button();
                                              btnExit.Text = "Exit";
                                              btnExit.Location = new Point(180, 180);
                                              btnExit.Size = new Size(80, 30);
                                              btnExit.Click += new EventHandler(BtnExitOnClick);
                                              
                                              // Adding controls to Form
                                              this.Controls.AddRange(new Control[] {lblGreeting, btnExit});
                               }
                               public void BtnExitOnClick(object sender, EventArgs e)
                               {
                                              Application.Exit();
                               }
               }
}


In the constructor of MyWindow, first we have set certain properties of the Form. In this code, we have also used the StartPosition property of the Form, which sets the start up position of the form on the screen. The type of this property is an enumeration called ‘FormStartPosition’. We have set the start position of the form to the center of the screen.

The new inclusion in the code is the Exit button called ‘btnExit’. We have created the button using the base class System.Windows.Forms.Button. Later, we set various properties of the button like its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also registered this event handler to the btnExit’s Click event (To understand the event handling in C#, see lesson 10 of the C# school). In the end, we have added a label and button to the form’s Controls collection. Note that this time we have used AddRange() method of form class to add an array of controls to the Controls collection of form. This method takes an array of type Control as its parameter.

The output of the code will be


Now you can press either the Exit Button or the close button at title bar to exit the application.

What is the architecture of .NET win form applications?

C# Version

WinForm Architecture As stated earlier, .NET provides WinForm and other controls through base classes in the System.Windows.Forms namespace. The class System.Windows.Forms.Form is the base class of all WinForms in .NET. In order to design a windows application, we need: 1. Create a Windows Application project in Visual Studio.NET or add references to System.Windows.Forms and System.Drawing to your current project. If you are not using Visual Studio at all, use /reference option of the command line compiler to add these assemblies. 2. Write a new class to represent the WinForm and derive it from System.Windows.Forms.Form class as
               class MyForm : System.Windows.Form
               {
                               ...
               }
3. Instantiate various controls, set their appropriate properties and add these to MyForm’s Controls collection. 4. Write another class containing the Main() method. In the Main() method, call the System.Application.Run() method by supplying it an instance of MyForm.
               class Test
               {
                               static void Main()
                               {
                                              Application.Run(new MyForm());
                              }
               }
The Application.Run() method registers your form as a windows application in the operating system so that it may receive event messages from the Windows Operating System.

VB.NET Version

WinForm Architecture As stated earlier, .NET provides the WinForm and other controls through base classes in the System.Windows.Forms namespace. The class System.Windows.Forms.Form is the base class of all WinForms in .NET. In order to design a windows application, we need to: 1.Create a Windows Application project in Visual Studio.NET, or add references to System.Windows.Forms and System.Drawing to your current project. If you are not using Visual Studio at all, use the /reference option of the command line compiler to add these assemblies. 2. Write a new class to represent the WinForm and derive it from the
System.Windows.Forms.Form class: 
Public Class MyForm
    Inherits System.Windows.Forms.Form 
    …
End Class


3. Instantiate various controls, set their appropriate properties and add these to MyForm's Controls collection. 4. Write another class containing the Main() method. In the Main() method, call the System.Application.Run() method, supplying it with an instance of
MyForm. 
Class Test
    Public Sub Main()
        Application.Run(New MyForm())
    End Sub
End Class


The Application.Run() method registers your form as a windows application in the operating system so that it may receive event messages from the Windows Operating System.

How do I provide the event handling for my form and controls using VS.NET?

Adding Event Handling You can provide event handling for forms and controls by implementing their respective event handlers. To implement an event handler for a form or control, go to Events tab of the properties window, and double click the desired event handler name. The form designer will add the event handler for the selected event in the source code of the application and take you there. If you want to implement a default event handler of the form or control, simply double click it.

For example, to add the event handling code for the Exit button in the Hello WinForm application (demonstrated in FAQ 5), simply double click the Exit button in the designer. It will create a new event handler for the Exit button’s Click event and take you to the source code as shown in the following figure

C# Version

Write the code to close the application (Application.Exit()) in the event handler. The IDE in fact has not only created the event handler but also has registered it with the Exit button’s Click event.

How do I prevent a user from resizing a form?

The following code shows how a Form's size can be restricted at runtime.
Place the following code in the load event of the form.
Public Class Form2
    Inherits System.Windows.Forms.Form
1.     Region " Windows Form Designer generated code "
2.      
 
        Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.MaximizeBox = False
    End Sub
End Class

How do I change the icon of the application I am working with?

Changing the Icon of your application is simple. Select Project->Properties. In the windows "style" section click on the "Icon" Button. Then make your choice

What basics should be remembered while developing win form apps?

Some Important Points for designing Windows Applications
  • Make your form layout simple and easy to understand. It is important that the user of your application finds it familiar. The behavior should be expected and should not surprise the user.
  • The Format menu of the Visual Studio.NET IDE is very useful when designing the form layout. It provides a number of useful options for alignment and size of the controls.
  • Almost all the controls have some similar properties like Location, Size, Enabled, Visible, TabIndex, etc. The TabIndex property is very important. It describes the sequence followed by the windows focus when the user presses the Tab button of keyboard.
  • Usually we don't change the Name property of labels as we don’t need to use the label variable in our code most of the time.
  • The controls should be named so that their purpose can be recognized, e.g., you may name the ‘Purchase’ button as btnPurchase, text box for entering email may be txtEmail and so on.
  • Although now it is not a standard convention, but it is useful to add a three letter prefix to the name of your controls so that they are recognizable with their name. Most of the developers used to follow the convention like prefixing Label with lbl (lblGreeting), TextBox with txt (txtComments), Button with btn (btnPurchase), CheckBox with cbx (cbxProgCS), RadioButton with rbn (rbnFullPayment) and GroupBox with gbx (gbxPaymentMode).

How do I make a splash screen in my win form application?

There is no built-in support for the splash screen in the Microsoft.NET win form applications. However, you can create a splash screen by creating a form with no title bar (by setting its FormBorderStyle to None), making it not appear in the taskbar (by setting its ShowInTaskbar property to false), making it the top most form (by setting) its TopMost property to true, and making it appear on the center of the screen (by setting its StartupPosition as CenterScreen).

You can now show this splash form when the main application is loading.

C# Version

private void Form1_Load(object sender, System.EventArgs e)
{
               this.Hide();
               Form2 frmSplash = new Form2();
               frmSplash.Show();
               frmSplash.Update();
               Thread.Sleep(5000);
               frmSplash.Close();
               this.Visible = true;
}

VB.NET Version

Private Sub Form1_Load(ByVal sender As System.Object, _
               yVal e As System.EventArgs) Handles MyBase.Load
Me.Hide()
Dim frmSplash As New Form2
frmSplash.Show()
frmSplash.Update()
Thread.Sleep(5000)
frmSplash.Close()
Me.Visible = True
End Sub

What does it mean by scrollable forms in .NET? How can make my own form scrollable?

.NET introduces with it a concept of scrollable forms. A scrollable form is just like an html page that can be scrolled. You can access its controls by scrolling it down or right; if the contents (controls) don’t fit in the form display area.

You can make a form scrollable by setting its AutScroll property to true

How do I set the first form to be loaded at application startup?

The first form to be loaded at the application startup is called the startup or main form of the application. You can set the startup form of the application by right clicking the target project node and selecting properties. It will show you the property pages for the project. Here in the Common PropertiesàGeneral, you can set the startup form by selecting its name from the drop down list of ‘Startup Object’.

C# Note

Remember that only those forms that have a valid Main() method can be selected as the startup object.

How do I add another form into my win form application?

To add and design a new form at design time, right click the target project node in the Solution Explorer and select AddàAdd Windows Form… This will add a new form; design it by placing controls and setting necessary properties.

To show the new form at run time, instantiate the new form and call its Show() or ShowDialog() method.

Let we name the new form as ‘MySecondForm’, then on the click event of the button of our first (startup) form, we can write the following code:

C# Version

MySecondForm frm2 = new MySecondForm();
frm2.Show();            // will present the non-modal form
// frm2.ShowDialog();              // will present the modal form

VB.NET Version

Dim frm2 As New MySecondForm()
frm2.Show()                            ' will present the non-modal form
' frm2.ShowDialog()                'will present the modal form

How do I display a message box in my form application?

To show the message box, call the MessageBox class’ Show() method. The message box is the modal form that notifies the user about certain event in the application and optionally takes the user feedback. The Show() is an static (C#) / Shared (VB.NET) method of the System.Windows.Forms.MessageBox class. It has a number of overloaded versions. The simplest one take the message text and display it in the message box.

C# Version

MessageBox.Show("Welcome to Win Form");

VB.NET Version

MessageBox.Show("Welcome to Win Form")


To add the title to the message box, call the MessageBox.Show() like:

C# Version

MessageBox.Show("Welcome to Win Form", "Greeting");

VB.NET Version

MessageBox.Show("Welcome to Win Form", "Greeting")


The following example code shows the message box with Yes, No, Cancel button to confirm application close and closes the application if the user selects the Yes button

C# Version

DialogResult dlgRes = null
dlgRes = MessageBox.Show(
               "Are you sure you want to close without saving the document", 
               "Confirm Document Close", 
MessageBoxButtons.YesNoCancel, 
               MessageBoxIcon.Question);
if(dlgRes == DialogResult.Yes)
{
               Application.Exit();
}

VB.NET Version

Dim dlgRes As DialogResult
dlgRes = MessageBox.Show( _
      "Are you sure you want to close without saving the document", _
      "Confirm Document Close", _
MessageBoxButtons.YesNoCancel, _
      MessageBoxIcon.Question)
If dlgRes = DialogResult.Yes Then
      Application.Exit()
End If

How do I exit my win form application programmatically?

To exit the win form application programmatically, call the Application.Exit() method.

C# Version

Application.Exit();

VB.NET Version

Application.Exit()

How do I close the form programmatically?

To close the form programmatically, call the Close() method of the form.

C# Version

myForm.Close();

VB.NET Version

myForm.Close()

How do I make and display a form without title bar?

To display your from without the title bar, set the FormBorderStyle property of the form to None

How do I make my form not to appear in the task bar?

To make your form not to appear in the task bar, set the ShowInTaskbar property of the form to false.

How do I change the icon of my form to be displayed at title bar?

You can change the icon of the form by changing its icon property. Remember that this property will only change the icon of the form and not of the application. To change the icon of the application or assembly, change the icon from the property pages of the project. The property pages for the project are displayed when you right click the project and select properties.

. How do I make my form non-resizable or fixed length?

You can make your form non-resizable or fixed length by setting its FormBorderStyle property to Fixed3D or FixedSingle or FixedDialog

How do I hide maximize, minimize and close box at the form title bar?

To disable the maximize box at the form title bar, set the Maximize property of the form to false.

To disable the minimize box at the form title bar, set the Minimize property of the form to false.

You can not hide only the close box from the form title bar using the form’s property.

Similarly, you can not only hide maximize or minimize boxes from the title window.

You can hide maximize and minimize boxes from the title bar by setting the FormBorderStyle property of the form to the FixedToolWindow or the SizableToolWindow. But remember that with FormBorderStyle set to the FixedToolWindow or SizableToolWindow, the form will not be displayed in the Windows task bar or in the window that appears when the user presses ALT+TAB.

You can hide the Control box from the title bar of the form by setting the ControlBox property of the form to false. This will hide the control box and system menu from the form window.

How do I show my form as a modal dialog?

To show your form as the Modal dialog, call the ShowDialog() method of the form to display it on the screen.

C# Version

myForm.ShowDialog();

VB.NET Version

myForm.ShowDialog()

What is the difference between modal and non-modal dialogs?

The modal form, when displayed on the screen, does not allow you to go and select any other form of the window. The typical example of the Modal form is the Message Box; you must select OK (or other appropriate) button to go back to other forms of the applications.

The Non modal form, on the other hand, does not prevent you from accessing other form windows of the application, when they are present on the screen using the Show() method of the form.

C# Version

myForm.Show();

VB.NET Version

myForm.Show()

How do I show my form?

You can show your hidden form or any other control by setting its ‘Visible’ property to True.

C# Version

myForm.Visible = True;

VB.NET Version

myForm.Visible = True

How do I hide my form?

You can hide your form or any other control by setting its Visible property to False.

C# Version

myForm.Visible = False;

VB.NET Version

myForm.Visible = False

What does it mean by Startup Window State of the form? How do I set the startup window state of the form?

The startup window state specifies whether the form should be displayed in normal, maximized or minimized state. It can be set using the WindowState property of the form. The data type of this property is System.Windows.Forms.FormWindowState enumeration, which has three members; Maximized, Minimized and Normal.

C# Version

myForm.WindowState = FormWindowState.Maximized;

VB.NET Version

myForm.WindowState = FormWindowState.Maximized

How do I set the initial (startup) size of the form?

The size property can be used to set the startup size of the form. The data type of the size property is System.Drawing.Size. The size can be set as:

C# Version

myForm.Size = new System.Drawing.Size(400, 300);

VB.NET Version

myForm.Size = New System.Drawing.Size(400, 300)

How do I set the startup position of the form?

To change the startup position of the form, select the form in the designer and change its StartPosition property. The StartPosition is an enumeration and has the following useful properties:
CenterScreen: The form should be displayed at the center of the screen
WindowsDefaultLocation: The form's startup position should be selected by the Windows Operating System
CenterParent: The form should be displayed at the center of the parent form. This option is useful when you are building an MDI (Multiple Document Interface) application. The MDI child form can be set, in this way, to be displayed at the center of the MDI parent form.

How do I change the application name?

To change the application name, change the name of the startup project by right clicking the project node in the solution explorer and selecting properties. It will show the property pages for the project. Here in the Common Properties -> General, you can change the assembly name to change the resulting executable (.exe) file name.

How do I change the title of my window?

Use the Text property of the Form to change the title of the form.

What are the lifetime events of a form?

Some important lifetime events of a form include:

Load: This event is fired when the form is first loaded in the program. It is called when the Form.Show() or Form.ShowDialog() method is called for the first time.

Activated: This event is triggered whenever the form gets the application focus. It is fired when the form is first loaded (along with Load event), when the form is brought in front, or when the form is restored from the minimized state.

VisibleChanged: It is called whenever the Visible property of the form is changed or the form is hidden or shown.

Deactivated: This event is triggered whenever the form loses the application focus. It is fired when the form is closed, when the form is brought into background, or when the form is minimized.

Closing: It is fired when the application wishes to be closed, or the application is in the process of close but has not yet closed.

Closed: It is raised when the application is finally closed.

How event handling is implemented in win form and .NET form controls with C#?

C# Version

Adding Event Handling A control exposes an event by defining its delegate. We can add our own event handler for the event by writing an event handler method and adding it to the event’s delegate.

For example, add a button labeled ‘Exit’ to the form of FAQ 8. The ‘Exit’ button will close the application when it is clicked. In .Net, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button’s Click event. Following is the code for this modified application
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
{
               class Test
               {
                               static void Main()
                               {
                                              Application.Run(new MyWindow());
                               }
               }
               class MyWindow : Form
               {
                               public MyWindow() : base()
                               {
                                              // Form
                                              this.Text = "My First Windows Application";
                                              this.Size = new Size(300, 300);
                                              this.StartPosition = FormStartPosition.CenterScreen;
                                              // Label
                                              Label lblGreeting = new Label();
                                              lblGreeting.Text = "Hello WinForm";
                                              lblGreeting.Location = new Point(100, 100);
                                              // Button
                                              Button btnExit = new Button();
                                              btnExit.Text = "Exit";
                                              btnExit.Location = new Point(180, 180);
                                              btnExit.Size = new Size(80, 30);
                                              btnExit.Click += new EventHandler(BtnExitOnClick);
                                              
                                              // Adding controls to Form
                                              this.Controls.AddRange(new Control[] {lblGreeting, btnExit});
                               }
                               public void BtnExitOnClick(object sender, EventArgs e)
                               {
                                              Application.Exit();
                               }
               }
}

We have highlighted the interested parts in the above code by bold formatting. We have created the Exit button called ‘btnExit’ using the class System.Windows.Forms.Button. Later, we set various properties of the button like its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also registered this event handler to the btnExit’s Click event (To understand the event handling in C#, see lesson 10 of the C# school). In the end, we have added a label and button to the form’s Controls collection.

The output of the code will be

Now you can press either the Exit Button or the close button at title bar to exit the application.

How do I minimize, maximize and restore my form programmatically?

You can minimize, maximize and restore the form by setting the WindowState property of the form. The following code example will minimize the form, wait for 2 seconds, restore the form, wait for 2 seconds and then maximize the form. I have written this code on the a button’s Click event.

C# Version

private void button1_Click(object sender, System.EventArgs e)
{
// Minimize the form window
               this.WindowState = FormWindowState.Minimized;
               Thread.Sleep(2000); // wait for 2 seconds
               // Restore the form window
               this.WindowState = FormWindowState.Normal;
                                              
               Thread.Sleep(2000); // wait for 2 seconds
               // Maximize the form window
               this.WindowState = FormWindowState.Maximized;
}

VB.NET Version

Private Sub Button1_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) _
Handles Button1.Click
' Minimize the form window
      Me.WindowState = FormWindowState.Minimized
      Thread.Sleep(2000)  ' wait for 2 seconds
      ' Restore the form window
      Me.WindowState = FormWindowState.Normal
      Thread.Sleep(2000)  ' wait for 2 seconds
      ' Maximize the form window
      Me.WindowState = FormWindowState.Maximized
End Sub


Note that the above code snippet is using the System.Threading.Thread class’ Sleep method to suspend the form for 2 seconds. Hence, you would be required to include the System.Threading namespace to your form class source code.

C# Version

Using System.Threading;

VB.NET Version

Imports System.Threading

WInForm Controls:-

What are win form controls? How they are represented in .NET framework class library?

A form may contain various user interface (UI) controls. The controls represent the visual components that allow user to interact with the application and perform the desired task. All the controls, in .Net, are represented by subclasses of System.Windows.Forms.Control class. Each form has a collection (named ‘Controls’) to store the constituent controls of the form. In fact, a form itself is a special type of control called Container Control, i.e., the Form class itself is derived from the ContainerControl class which is a subclass of the Control class. A container control, as the name suggests, may contain other controls. Other examples of the Container control include Panel and Tab Control.

Each control, and thus form, exposes a number of events that can be triggered on certain user action or application behavior. For example, a button raises Click event whenever it is clicked and the text box raises the TextChanged event whenever its text is changed. The application developer can write even handler to catch these events and perform corresponding action. Beside these, a form also has certain set of events called the form life cycle events. These events are triggered during the life cycle of form to indicate the current state of the form.

What are the fundamental and common properties of .NET controls?

Almost all the controls have some similar properties like Location, Size, Enabled, Visible, TabIndex, Name, Text, BacKColor, ForeColor, Font, etc. The TabIndex property is very important. It describes the sequence followed by the windows focus when the user presses the Tab button of keyboard

How do I set the tab order of the controls on the form?

To set the tab order of the controls on the form, select View -> Tab Order. This will start a wizard for setting the tab order. You can set the order of tab for the control by just clicking it in the same sequence as of required tab order.

What does it mean by anchoring of controls?

An anchoring is the property of the control to keep a specific distance with a particular edge of the window (or other containing control). You can anchor a control to any edge or side of the window, e.g., left, top, right, bottom, left and top, etc. If a control is anchored to the left of the window, it will keep the constant distance from the left side of the window; even when the window is resized. The constant distance that the control will keep with the window is the distance it has at the form startup or defined by its Location property. In the figure below, the button is anchored to the top edge of the window.

When the window is resized, it shifts itself on the form to keep the same distance from the top, see the figure below:

If we have defined the top and bottom anchoring and the form is resized, the control will resize itself to have the same distance from top and bottom. Consider the figure below; here the button is anchored top and bottom

When the form is resized, the button resizes itself to keep the same distance from top and bottom

The default anchoring of a control is left and top.

How do I set the anchoring property of my controls?

To change the anchoring property of the control, set the Anchor property of the control from the properties window. When you click the Anchor property of the control in the properties window, Visual Studio.NET will show you a tab to set the edges with which you wish to anchor the controlHow do I set the docking property of my controls?

To change the docking property of the control, set the Dock property of the control from the properties window. When you click the Dock property of the control in the properties window, Visual Studio.NET will show you a tab to set the edges with which you wish to dock the control

How do I set the width of a ComboBox to fit the contents?

Move through the index items to find the longest item by character length using the MeasureString function. Use the this value as the ComboBox width.
System.Drawing.Graphics g = comboBox1.CreateGraphics(); 
 
float maxWidth = 0f; 
 
foreach(object o in comboBox1.Items) 
 
{ 
 
float w = g.MeasureString(o.ToString(), comboBox1.Font).Width; 
'checking the combobox for the longest text
if(w > maxWidth) 
maxWidth = w; 
'setting the width by checking the longest text
} 
g.Dispose(); 
comboBox1.Width = (int) maxWidth

How do I set the color and font in a RichEditBox?

Use the SelectionFont and SelectionColor properties to set the font and color of a RichEditBox. The following code will set the "selected text" to a blue-italic-verdana font set.

Note. If no text is selected then any all new text will be blue-italic-verdana within the RichEditBox.


 
RichTextBox1.Focus(); 
 
RichTextBox1.SelectionColor = Color.Blue; 
 
RichTextBox1.SelectionFont = new Font ("Verdana", 12, FontStyle.Italic);

How do I browse and read a text file into a TextBox?

You use the OpenFileDialog to implement this functionailty.
 
using System.Text; 
using System.IO; 
private void button1_Click(object sender, System.EventArgs e) 
{ 
  OpenFileDialog ofd = new OpenFileDialog(); 
  ofd.Title = "Open the text file you wish" ; 
  ofd.InitialDirectory = "c:\" ; 
  ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ; 
 
 if(ofd.ShowDialog() == DialogResult.OK) 
   { 
    StreamReader sr = File.OpenText(ofd.FileName); 
    string s = sr.ReadLine(); 
    StringBuilder sb = new StringBuilder(); 
    while (s != null) 
      { 
       sb.Append(s); 
       s = sr.ReadLine(); 
      } 
      sr.Close(); 
      textBox1.Text = sb.ToString(); 
   } 

How to use the Splitter control?

The Splitter control is used to resize other controls. The purpose of this is to save space on the form.
This control can be very useful when you are working with controls both at design time and run time (which are not visible at design time).

How do I place restriction when entering some text in a textbox?

You can restrict a user from entering text against a set pattern. Or you can request the user only to enters certain type of characters. E.g. Only a single digit number or a double digit number and so on. To control the input, use the KeyPress event like below:
Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles 
TextBox1.KeyPress
If(e.KeyChar < "10" Or e.KeyChar > "100") Then
MessageBox.Show("Enter Double Digits")
End If
End Sub

How do I access controls on another Form?

To access controls on other WinForms follow the example. This example reads the text in a textbox from other form and displays it in the textbox on the current form.

Open two forms (form1 and form2), add a Command Button and a Textbox to Form1 and a Textbox to Form2.

The following code relates to form1.
Public Class Form1
Inherits System.Windows.Forms.Form
Dim NewWindow As New Form2()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
NewWindow.Show()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = NewWindow.TextBox1.Text
End Sub
End Class


When you run the code, Both Form1 and Form2 are displayed. Enter some text in the Textbox on Form2 and click the button on form1. The text entered in the Textbox in Form2 will be displayed in the Textbox in Form1.

How can I access a Website/Webpage with a VB.NET LinkLabel control?

To access a Website or a Webpage using a VB.NET application. Drag a LinkLabel control and write the following code in it’s click event.
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As 
System.Windows.Forms.LinkLabelLinkClickedEventArgs)Handles_
LinkLabel1.LinkClicked
System.Diagnostics.Process.Start("www.yahoo.com")
End Sub

Upon running the application,click on the Text on the LinkLabel. The website, Yahoo.com will open in a new browser.

How do I add items to a ComboBox and sort them?

The following code shows how to add items to a ComboBox.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add(“India”)
ComboBox1.Items.Add(“Australia”)
ComboBox1.Items.Add(“Sweden”)
ComboBox1.Items.Add(“Spain”)
ComboBox1.Items.Add(“England”)
ComboBox1.Items.Add(“United States”)
ComboBox1.Items.Add(“Russia”)
ComboBox1.Items.Add(“China”)
ComboBox1.Items.Add(“Japan”)
ComboBox1.Items.Add(“New Zeland”)
End Sub


To sort the items alpahbetically, select the .Sorted property and set it to True.

How do I load a picture into the PictureBox control?

To load a Picture into the PictureBox control drag a PictureBox control and a Command Button from the Toolbox. When you click the Command Button, the picture you specified will be loaded into the Picturebox.

The following code is a demonstration.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Image=Image.FromFile("C:\images\image.gif")
'Assuming you have a folder named images in C: drive and a gif image in that
End Sub

How do I add a control to windows form at runtime?

To add a control to a Form at Runtime, firstly decide which control is needed. Set all relevent properties and finally use the Controls.Add(controlname) function.

An an example of how to add a TextBox:
Dim tb as TextBox = New TextBox() 
'declaring a textbox 
tb.Size = New Size(130, 25) 
'setting the size for the textbox
tb.Location = New Point( 50, 70) 
'setting the location 
tb.Text = "Textbox1" 
'setting the text
Me.Controls.Add(tb)  
'adding the textbox to the form

How to create an "Explorer style" application in VB.NET?

Displaying all the drives, folders and files in an application like "Explorer" can be done easily in VB.NET. To do this follow these simple instructions:

Open a new project Add a Command Button to the Form. Place the following code in the click event of the command button.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
        Dim expl As New ExplorerStyleViewer()
        expl.Show()
End Sub

What is a Tooltip control and how should I use it?

A Tooltip is a tag that displays some text when an ojects Mouse Over event is triggered. This is usually a decription of the object or the action that will follow if the object is say for example clicked.

Assume that there is a TextBox on a Form and we want to display a description when the mouse is over the TextBox.

Below is an example
Private Sub Form5_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(TextBox1, "Enter Some text")
'using the SetToolTip method to set the tip for the TextBox and the text that should appear
End Sub

Windows Programming Interview Questions

1. Which controls can not be placed in MDI ?
2. List out controls which does not have events
3. Which property of textbox cannot be changed at runtime. What is the max size of textbox?
4. How many system controls are available
5. ___,_____ and ____ container objects.
6. strech___ Property is to compress a image in image control.
7. ___,___ and __ are difference between image and picture controls.
8. Is it possible to set a shortcut key for label.
9. What is the default property of data control?
10. ___,__,___ are the type of combo box?
11. __ no of controls in form.
12. OLE is used for _______
13. What is the need of tabindex property is label control.
14. ___ is the control used to call a windows application.
15. Clear property is available in ____,___ control.
16. ___ Property is used to count no. of items in a combobox.
17. ___ is a property to resize a label control according to your caption.
18. Which controls have refresh method.
19. ___ property is used to change to ___ value to access a identity column in datacontrols.
20. _____ is the property to ___,____,____ are valid for recordsource property of dat control.
21. To find the current record position in data control.
22. Timer control contains ________ no. of events.
23. ____ property is used to lock a textbox to enter data.
24. What is the need of z-order method?
25. ____ is the difference between Listindex and Tab index.
26. ____ property of menu cannot be set at run time.
27. Can you create a tabletype of recordset in Jet - connected ODBC dbengine.
28. Difference between listbox and combo box.
29. What are the new events in textbox that has been included in VB
30. 0
31. Can you create a Updatecascade, Deletecascade relation in Ms- Access? If no, give on eample.
32. _____ collection in recordset used to assign a value from textbox to table columns without making abinding in datacontrol.
33. ____ argument can be used to make a menu item into bold.
34. What is the difference between Msgbox Statement and MsgboxQ function?
35. What is.the difference between queryunload and unload in form?
36. ___,___ arguments will be used to run a executable program in shell function
37. ___ property used to add a menus at runtime.
38. What is the difference between modal and module-less window?
39. ___ VB constant make the menu item in centre.
40. ___ method used to move a recordset pointer in nth position in DAG.
41. To validate a range of values for a property whenever the property values changes,which type of property procedure you use?
42. What are 3 main differences between flexgrid control and dbgrid control?
43. What is the difference between change event in normal combobox and dbcombobox?
44. To populate a single column value which dbcontrols you to use?
45. What is ODBC?
46. Parts of ODBC?
47. What is DSN?
48. What is DAO?
49. Types of cursors in DAO?
50. Types of LockEdits in DAO? 51 .Types of Recordsets.
51. Difference between Tabletype and Snapshot?
52. Draw Sequence Modal of DAO? Explain.
53. Difference between Dynaset and Snapshot?
54. Difference between Recordset and Querydef?
55. What is the use of Tabledef?
56. Default cursor Type and LockEdit type in DAO?
57. What is the default workspace?
58. 1s it posible to Create Tables Through Querydef?
59. It is possible to access Text (x.txt) files? Explain.
60. What is ODBC Direct and Microsoft Jet Database Engine ?
61. Is it possible to Manipulate data through flexgrid? Explain.
62. Types of DBCombo boxes
63. What do you mean by Databound Controls? Explain.
64. What is RDO?
65. Types of cursors in RDO.
66. Types of LockEdits in RDO.
67. Types of LockEdits in RDO.
68. Types of Resultsets.
69. Difference between Recordset and Resultsets.
70. Explain Default cursor Type and LockEdits type in RDO
71. Draw Sequence Modal of RDO? Explain.
72. What is meant by Establish Connection in RDO?
73. Is it possible to Access BackEnd procedures? Explain.
74. What is OLE? Explain.
75. What is DDE?
76. Difference between Linked Object and Embedded Object?
77. Explain OLE Drag and Drop.
78. Difference between DDE and OLE.
79. What is the difference between Object and Class?
80. Give brief description about class?
81. Does VB support object-oriented concepts? Explain..
82. Difference between Class Module and Standard Module?
83. Explain Get, Let, Set Properties.
84. Difference Types of Procedures in VB?
85. What is the use of NEW Keyword? Explain.
86. What is constructors and distructors.
87. Types of Modal windows in VB.
88. What is ActiveX? Explain.
89. Types of ActiveX Components in VB?
90. Difference between ActiveX Control and Standard Control.
91. Difference between ActiveX Exe and Dll.
92. What is instantiating?
93. Advantage of ActiveX Dll over Active Exe.
94. Difference Types of Instancing Property in ActiveX Dll and Exe.
95. What is ActiveX Dll and ActiveX Exe?
96. Write the steps in Creating ActiveX Dll and Active Exe?
97. Explain the differences between ActiveX Dll and ActiveX Exe?
98. How would you use ActiveX Dll and ActiveX Exe in your application?
99. How would you access objects created in ActiveX Exe and ActiveX D1T
100. What is the use of ActiveX Documents?
101. What is ActiveX Document?
102. What is the use of Visual Basic Document file?
103. What is hyperlink?
104. How would you create Visual basic Document file?
105. What is Internet Explorer and its uses?
106. How would you navigate between one document to another document in Internet Explorer ?
107. How would you run your ActiveX Document Dll?
108. How would you view html code in Active Server Pages?
109. How would you cre.ate your application in DHTML?
110. What is ActiveX Control?
111. Write the Steps in Creating an ActiveX Control?
112. How would you attach an ActiveX control in Your Application?
113. How would you create properties in ActiveX Control?
114. What is the-use of property page Wizard in ActiveX Control?
115. How would you add elements in TreevieW Control.
116. What are the types of line styles available in Treeview Control?
117. What is the use of Imagelist Controls
118. How would you attach pictures in Treeview Control?
119. What are the uses of List View Control?
120. Explain the types of Views in Listview Control.
121. How would you attach pictures in column headers of List View Control?
122. How would you add column headers in listview control?
123. How would you add elements and pictures to listitems in listview control?
124. How would you activate animation control?
125. What is the use of progress Bar Control?
126. How would you find out the value property in Slider Bar Control?
127. What is the use of Data Form Wizard?
128. How would you map properties to controls by using ActiveX Control Interface Wizard?
129. How would you convert a form into document?
130. How would you Create a Query Builder and Explain its uses
131. How would you create properties by using class Builder Wizard?
132. HTML stands for What? Use of HTML ?
133. Whether HTML supports multimedia: and document links?
134. DHTML Is used for what?
135. What do you mean by HTTP?
136. What is the use of Hyperlink control for DHTML applications?
137. How can you Navigate from the DHTML application to another DHTML application? .
138. What are the Internet tools available in VB
139. 0?
140. Explain the usage of Web Browser Control?
141. What do you mean by ADO?
142. What is the difference Between ADO and other data access objects0
143. What is OLEDB?
144. What are the important components of OLEDB?
145. Through which protocol OLEDB components are interfaced?
146. It possible to call OLEDB’s Features directly in VB without using any control?
147. What type of databases you can access through AD I Data Access Object?
148. How many objects resides in ADO ?
.
149. What is the use of Connection object?
150. What is the use of command Object?
151. Record set object consists of what?
152. What is the use of parameters collection?
153. Which type of object requires this object?
154. Is it possible to call backend procedures with ADO control?
155. Is there any Edit method in ADO Data Access method?
156. How can you check whether a record is valid record or Invalid record using ADO control or Object?
157. What do you mean by provider?
158. What type of record sets are available in ADO?
159. Is it possible to call oracle database through ADO control or Object?
160. How many File System Controls are there ? Explain.
161. How can you filter out specific type of file using file system controls?
162. How can you get selected file from file system Control?
163. How many ways we can access file using VB?
164. Which method is preferred to save data like database to the disk?
165. How to get free file location in memory?
166. How to find size of the file. Which method or function is used to occomplish this?
167. Using which type we can access file line by line?
168. Which method is used to write context Into file?
169. How can you read content from file?
170. Binary Access-method is used to access file in which manner?
171. How can you check Beginning and End of the file?
172. What is the use of Scalewidth and ScaleHeight Proeperty?
173. What is the use of Active Control Property?
174. How can you save and Get data from Clipboard/
175. What are the types of Error?
176. In which areas the Error occurs?
177. What are the tools available for Debug in VB?
178. What is the use of Immediate, Local Window?
179. What is the use of debug Window?
180. How can you Implement windows functionality in VB?
181. How many types of API functions are available in VB?
182. How can you Add API functions to your Application?
183. How to get Cursor position using API?
184. Is it possible to change menu runtime using API? If yes? Specify the function names.
185. What are the types of API Types.
186. Scope of API’s can be of types, what are they? Why API functions are Required?