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.

Controls.Add(dynamicButton)

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:
Example:
//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);
myxlApp.Quit();
releaseObject(myxlWorkSheet);
releaseObject(myxlWorkBook);
releaseObject(myxlApp);
//Note Release all object then show excel
System.Diagnostics.Process.Start("D:\1.xlsx");
// Exception handlers
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception exp)
{
obj = null;
MessageBox.Show("Fail to release the Object " + exp.ToString());
}
finally
{
GC.Collect();
}
}

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);
myXlsApp.Quit();
releaseObject(myXlsWorkSheet);
releaseObject(myXlsWorkBook);
releaseObject(myXlsApp);
MessageBox.Show("Excel file created , you can find the file D:\samples.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
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.