Jun 26, 2012

How to Create Button in .NET

Today, I will focus on how to create button in .NET. As we all know that a user control can be created in both design-time and run-time.

Create button at design-time
This is not the point of this post, as we all know: To create a button control at design-time, you simply drag and drop a Label control from Toolbox to a Form. After you drag and drop a Label on a Form. After then you can move it around and resize it using mouse and set its properties and events.

Create button at run-time
This is the focus of my post. To dinamicly create a button in .NET
1. Create an instance of Button class
     Button dynamicButton = new Button();
2. Set Button class properties
    dynamicButton.Location = new Point(30, 70);
    dynamicButton.Height = 50;
    dynamicButton.Width = 300;
    // Set background and foreground
    dynamicButton.BackColor = Color.Red;
    dynamicButton.ForeColor = Color.Blue;
    dynamicButton.Text = "I am Dynamic Button";
    dynamicButton.Name = "DynamicButton";
    dynamicButton.Font = new Font("Georgia", 16);
3. Add Button control
     A Button control is used to process the button click event. We can attach a button click event handler at run-time by setting its Click event to an EventHandler obect. The EventHandler takes a parameter of an event handler. The Click event is attached in the following code snippet.

// Add a Button Click Event handler
dynamicButton.Click += new EventHandler(DynamicButton_Click);

Now the last step is adding a Button control to the Form. The Form.Controls.Add method is used to add a control to a Form. The following code snippet adds a Button control to the current Form.


Jun 24, 2012

Custom Controls in .NET

Today, we will talk about Controls in .NET. As we all know, a user control is essentially a component with a visual representation. As such, it might consist of one or more Windows Forms controls, components, or blocks of code that can extend functionality by validating user input, modifying display properties, or performing other tasks required by the author. User controls can be placed on Windows Forms in the same manner as other controls.  However a custom controls never end that simple, so there are types of costom controls like this:

4 Types of Custom Controls in .NET

User controls are the simplest type of control. They inherit from the System.Windows.Forms.UserControl class, and follow a model of composition.
Usually, user controls combine more than one control in a logical unit (like a group of text boxes for entering address information).
Inherited controls are generally more powerful and flexible. With an inherited control, you choose the existing .NET control that is closest to what you want to provide. Then, you derive a custom class that overrides or adds properties and methods.
Owner-drawn controls generally use GDI+ drawing routines to generate their interfaces from scratch. Because of this, they tend to inherit from a base class like System.Windows.Forms.Control. Owner-drawn controls require the most work and provide the most customizable user interface.
Extender providers, which aren't necessarily controls at all. These components add features to other controls on a form, and provide a remarkable way to implement extensible user interface.

Reasons of Custom Controls in .NET

To create controls that abstract away unimportant details and are tailored for a specific type of data. You saw this model in Chapter 6 with custom ListView and TreeView examples.
To create controls that provide entirely new functionality, or just combine existing UI elements in a unique way.
To create controls with a distinct original look, or ones that mimic popular controls in professional applications (like Microsoft's Outlook bar) that
aren't available to the masses.
In .NET, creating a custom control is as easy as creating an ordinary class. You simply inherit from the best possible ancestor and add the specific features you need. Best of all, you can create a custom control class as part of an existing project, and then decide later to place it in a separate assembly that can be shared with other programmers.

Ways of adding user controls:
 User control can be added at design-time or run-time. Other controls is usually added at run-time.

Jun 20, 2012

Label in NET

Labels are one of the most frequently used C# control. We can use the Label control to display text in a set location on the page. Label controls can also be used to add descriptive text to a Form to provide the user with helpful information. But label control does not participate in user input or capture mouse or keyboard events. The Label class is defined in the System.Windows.Forms namespace. Here will discuss how to manage label in C#.NET.

A. Two ways of creating lables in .NET

1. Create label in design time

To create a Label control at design-time, you simply drag and drop a Label control from Toolbox to a Form. After you drag and drop a Label on a Form. After then you can move it around and resize it using mouse and set its properties and events.

2. Create label in run time

As we have said before, the Label class is defined in the System.Windows.Forms namespace and it represents a Label control.The following code snippet creates a Label control object.
// Create a Label object
Label myLabel = new Label();

B. Setting Label Properties
The easiest way to set properties is from the Properties Window. open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like:

Of course, We can set its properties by code in run time:
//set its name
myLabel.Name = "DynamicLabel";
//set label text
myLabel.Text = "I am Dynamic Label";
myLabel.TextAlign  = HorizontalAlignment.Center;
int size = myLabel.TextLength;

Type by Yourself- A Good Habit

It is better for you to type code and not just copy and paste the code samples here.
Reading a tutorial or a book, it is often helpful to type the code into the compiler and run it. Typing it yourself will help you to get used to the typical typing errors that cause problems and it will force you to pay attention to the details of programming syntax. Typing your program will also familiarize you with the general structure of programs and with the use of common commands. After running an example program - and after making certain that you understand how it works - you should experiment with it: play with the program and test your own ideas. By seeing which modifications cause problems and which sections of the code are most important to the function of the program, you should learn quite a bit about programming.

Remember: Every Line of code will be a bit step of your progress.

Jun 19, 2012

Open Excel-.NET

Today I will explains how to open and read an Excel file through C#.We also use Microsoft Excel 14.0 Object Library in project as reference to open Excel files . 

Three Steps to Open Excel in .NET 
Step 1 Create a new project and Add Microsoft Excel 14.0 Object Library as reference.
Step 2 Add namespace: using Excel = Microsoft.Office.Interop.Excel.
Step 3 Add methods to open Excel

Check the Code samples below
//declare parts
Excel.Application myxlApp;
Excel.Workbook myxlWorkBook;
Excel.Worksheet myxlWorkSheet;
object misValue = System.Reflection.Missing.Value;
// Open Excel file
myxlApp = new Excel.Application();
myxlWorkBook = myxlApp.Workbooks.Open("D:\samples.xlsx", 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
myxlWorkSheet = (Excel.Worksheet)myxlWorkBook.Worksheets.get_Item(1);
// show Excel B1 Cell Contents.
MessageBox.Show(myxlWorkSheet.get_Range("B1", "B1").Value2.ToString());
//A good habit to close file and release object
myxlWorkBook.Close(true, misValue, misValue);
//Note Release all object then show excel
// Exception handlers
private void releaseObject(object obj)
obj = null;
catch (Exception exp)
obj = null;
MessageBox.Show("Fail to release the Object " + exp.ToString());

Jun 17, 2012

Easily Create Excel in .NET-Excel Object Model

As we all know that there are three ways to manage Excel files in .NET. Excel Object Model is one choice and the other is using Microsoft Jet Engineto connecting Excel; the third way is to get a 3rd party component to server as an interface.
Three Steps to Create Excel via C#.NET
Step 1 Add the Microsoft Excel Object Library to your project(14.0 or 12.0)
Create a new project and add the Microsoft Excel Object Library to you project.
Right click your project reference, choose add reference,  from .com tag, locate Microsoft Excel Object Library to add in.
Step 2 Using Namespace
using Excel = Microsoft.Office.Interop.Excel;
Step 3 Create Excel File in .NET
Excel.Application myXlsApp ;
Excel.Workbook myXlsWorkBook ;
Excel.Worksheet myXlsWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = myXlsApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)myXlsWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://www.e-iceblue.com";
myXlsWorkBook.SaveAs("D:\samples.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
myXlsWorkBook.Close(true, misValue, misValue);
MessageBox.Show("Excel file created , you can find the file D:\samples.xls");
private void releaseObject(object obj)
obj = null;
catch (Exception ex)
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
Press F5 to execute this program , You will get an Excel file in D discs.

Jun 7, 2012

Work with Excel Workbook in .NET

From day on,I will also post some advanced technology .NET at the same time as I begin in .NET step by step. An advanced technology is to work with Excel in .NET. First question to answer how many ways and how to work with Excel in .NET.
Work Excel workbook in .NET
There are three different ways to work with Excel workbook in C#.  Of course, every way have its pros and cons which I will analyse below.
1. Use Excel InterOp Objects. This way is pretty easy for beginner, which is why I start with. Meanwhile,this way requires you to installed  Excel  in the development environment. This is a binding if you are going to make a product which is to be distributed.
2. Take use of OleDb data providers for Excel which is free with Windows. But notice that there is one limitation, you can access only data using this technique. You cannot do formatting through this technique.
3.Get a 3rd party library involved. It will  act as an interface between your program and the Excel.  Generally speaking, this way is very easy and powerful to develop, but it costs.

In my following post, normal I will ignore the 3rd party library unless it is necessary. 

Variable Types in C#.NET

In this post, I will describe Variable Types in C#.NET. As we all know, A variable can be compared to a storage room, and is essential for the programmer. Every variable has a type that represents what values can be stored in the variable.  So is in C#.NET. And C# is a type-safe language, and the the compiler guarantees that values stored in variables are always of the appropriate type.
Basicly speaking, there are two types of variable in C#.NET- value type and reference type.

Value type.

Value types directly contain a values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference(or simple address) to the object but not the object itself.

All value types are derived implicitly from the System.ValueType.For example, int is an alias of System.Int32. For a complete list of aliases, see Built-In Types Table

Unlike reference types, it is not possible to derive a new type from a value type. However, like reference types, structs can implement interfaces.

Unlike reference types, it is not possible for a value type to contain the null value. However, the nullable types feature does allow values types to be assigned to null

Each value type has an implicit default constructor that initializes the default value of that type. For information on default values of value types.
A picture of value type from msdn.

Reference Type:
Variables of reference types, referred to as objects, store references to the actual data. This section introduces the following keywords used to declare reference types: class,interface,delegate;
two built-in reference types: object,string.

Jun 4, 2012

Talking Several Language in or out .NET

According TIOBE Programming Community Index for May 2012. Below demonstrates the programming language rank in May 2012(Top 20 of them )
As we can see in the picture above, C and Java hold about 30% of the programming market and about twice of C++.
C and C++ 
The two language is quite used in tradition field, and changed little.

The quick rise of Java is due to Android development and shall continue to grow large.


This languge is primarily used to develop for Apple app.

C# ( VB.NET)

It is the language that used in .NET platform so that it can better exhibit its talent.

New language adoption appears to be much harder than expected. The main reason for this is probably that it is very difficult to migrate a large code base from one language to another one. So changes are slow. But even if we take this into account there are no new languages that show a slow but constant uprise.

So C#/VB.NET performs pretty better.

Generally speaking,C# is an Object Oriented Language , introduced in the .NET Framework. C# is a professional programming language and is very similar to C++ in many ways. We can implement the Object Oriented concepts like encapsulation, inheritance, and polymorphism in C# programming development .

C# is a Simple, Powerful , general-purpose and Type-Safe language also Case Sensitive . We can develop C# projects in Visual Studio Environment , a powerful tool-rich programming environment from Microsoft. We can create console based applications as well as windows based applications from C# environment. C# Coding style is very similar to C++ and JAVA , so the developers who are familiar with those languages can pick up C# coding quickly. That is the reason why I give all of examples in C#.NET.

VB.NET is another primary language used to program on the same environment as C#. Both languages are use the same framework and they both precompiled into the same byte code and then it is compiled and run at runtime. So we can say VB.NET and C# are functionally equivalent.

As for Java and C#,
They are two different Object Oriented Languages , both share some similarities and hold differences. The C# and JAVA derived from their own single ancestor Class "Object". All Classes in C# are descended from System.Object Class and in JAVA all classes are subclasses of java.lang.Object Class.

Both C# and JAVA have their own runtime environments . C# source codes are compiled to MSIL-Microsoft Intermediate Language and during the execution time runs it with the help of runtime environments - Common Language Runtime. Like that JAVA source codes are compiled to Java Byte Code and during the execution time runs it with the help of runtime environments - Java Virtual Machine (JVM). Both C# and JAVA supports native compilation via Just In Time compilers.

More over both C# and JAVA have their own Garbage Collector. In the case of keywords comparison some keywords are similar as well as some keywords are different also. The following are the examples of few similar and different keywords.

Similar Keywords examples
class , new , if , case , for , do , while , continue , int , char , double , null

How to Learn .NET

Quite probable that every readers gone ask how to learn .NET-Answer to this question is to refer to suitable books and ask export, keep coding.

Books for .NET
Truly, there is no such a book that suits every one, so I am now in a difficulty to find the suitable book. Fortunately, I find this good writing about top 10 .NET books: http://dotnet.dzone.com/articles/dzones-top-10-net-books.

Export for .NET 

The same that no one could be an export to all .NET technology, so here export means several online help available for every one.
1. Of course: MSDN this is a gather place for every .NET lovers. Feel free to seek help.
2. My favorite: Codeproject. The home for any developer/programmer. Some of the resource I used here is stolen from codeproject. But promise don't tell them.  LOL.


There had never been a somebody that came to be a export for any programming language.  So keep coding, error cames, ask export and then keep on.

That is what in my mind  the moment. Whenever I recall some missing, I will came back and add on secretly.

Jun 3, 2012

How .NET Works

Today, I will show how .NET works.

Understand .NET Framework Architecture
That is just a basic introduction for .NET, as for more details, please refer to two links I listed at last-I thought that can help everybody who want to know about .NET framework.
The .NET Framework has two components: the .NET Framework class library and the common language runtime.
The .NET Framework class library facilitates types (CTS) that are common to all .NET languages.
The common language runtime consists of (class loader) that load the IL code of a program into the runtime, which compiles the IL code into native code, and executes and manage the code to enforce security and type safety, and provide thread support.

 The simple introduction and the two pictures just help you to get a basic idea of how .NET works. Please check the two links I listed below.

Jun 2, 2012

Talks of .NET

Before we write .NET, it is better to give a brief introduction of .NET platform.

What is .NET.

The .NET Framework is a software framework developed by Microsoft that runs primarily on Microsoft Windows. Though it is a new computing platform  that simplifies application development in the highly distributed environment of the internet.However .NET is much more than just a platform for developing for the internet, but it is intended for this purpose predominantly, because here, others methods have failed in the past. .NET includes a large library and provides language interoperability across several programming languages(C#,VB,J#,C++). Programs written for the .NET Framework execute in a software environment, known as the Common Language Runtime (CLR), an application virtual machine that provides important services such as security, memory management, and exception handling. The class library and the CLR together constitute the .NET Framework.

The .NET Framework has been developed to cater to the following objectives and requirements:

    To provide a consistent object-oriented environment to develop applications.
    To provide a code execution environment that simplifies deployment and versioning.
    To provide a code execution environment that guarantees the safety of the code that is executing. This includes both code developed internally by an organization or for code developed by 3rd party vendors.
    To provide a code execution environment that eliminates the issues faced by scripted environments with respect to performance.
    To provide a common programming model where the choice of a programming language becomes a matter of choice.

How .NET Comes

The world of computing till date has been chaotic. We have had various languages struggling to inter operate with each other, developers undergoing huge learning curves to shift from one language to another or from one application type to another, non-standard ways of modeling applications and designing solutions and huge syntactic differences between languages. The list goes on....

Past years have seen some solace in the form of enterprise "glue" applications and standards like COM, which put-forth a binary standard of interoperability between application components. But in reality, this was not always true (VB COM found it very difficult to take on VC++ COM). Also, as applications increased in their reach, it was found that rather than re-inventing the wheel for a solution, it was better to take the "service" of another applications specialized for a piece of work.

Thus from a paradigm where applications replicated code to provide common services, we have moved to a paradigm where applications are built as "collaborative units" of components working together. This simple shift has led to the collapse of the current set of architectures and demanded a new programming model.

Development of .NET

I will present how .NET platform develops during those years by a screenshot from Wiki:

That is a simple of introduction to .NET. For more information, please see .NET in Wiki.

Jun 1, 2012

All About .NET and Me

I grew up in a world where Windows open for every one, of course, not free, and in a long period, Apple never fell to my head. So I am curious about Microsoft and with .NET coming up, I am absolutely crazy about this new technology. That is the reason promote me to writing this blog.

How will I Post

Normally, I will post one per day. Most of my post will be exampled in both C# and VB.NET.I will keep to go through from basic to advanced fields in .NET platform; from technology to interview questions.

What I Wish

I wish to contribute what I can to the development and make .NET more close with every one. Light up our life.