You are on page 1of 250

C# Crystal Reports Tutorial

Crystal Report is a Reporting Application that can generate reports from various Data Sources like Databases , XML files etc.. The
Visual Studio.NET Integrated Development Environment comes with Crystal Reports tools. The Crystal Reports makes it easy to create
simple reports, and also has comprehensive tools that you need to produce complex or specialized reports in csharp and other
programming languages.
Crystal Reports is compatible with most popular development environments like C# , VB.NET etc. You can use the Crystal Reports
Designer in Visual Studio .NET to create a new report or modify an existing report.
From the following sections you can find useful resources for generating customized reports from Crystal Reports with C# .
For generating Crystal Reports from C# , we need to connect a database and some tables with data. In the following section you can see
how to create a sample Database and Tables and the data for running of the following Crystal Reports - C# Tutorial . All examples in
the CSharp Crystal Reports Tutorial is based on the following database .

First we have to create a database named it as "crystaldb"


Create DataBase "crystaldb"

In the crystaldb database , create three tables


OrderMaster , OrderDetails , Product .
The Table Structure follows :
OrderMaster
OrderMaster_id
OrderMaster_date
OrderMaster_customer
OrderMaster_createduser
OrderDetails
OrderDetails_id
OrderDetails_masterid
OrderDetails_productid
OrderDetails_qty
Product
Product_id
Product_name
Product_price
The following picture shows the relation of tables in crystaldb database :

SQL command for creating tables are follows :

CREATE TABLE [dbo].[OrderMaster] (


[OrderMaster_id] [int] NOT NULL ,
[OrderMaster_date] [datetime] NULL ,
[OrderMaster_customername] [varchar] (50),
[OrderMaster_createduser] [varchar] (50)
) ON [PRIMARY]
CREATE TABLE [dbo].[OrderDetails] (
[OrderDetails_id] [int] NOT NULL ,
[OrderDetails_masterid] [int] NULL ,
[OrderDetails_productid] [int] NULL ,
[OrderDetails_qty] [int] NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Product] (
[Product_id] [int] NOT NULL ,
[Product_name] [varchar] (50) ,
[Product_price] [numeric](18, 0) NULL
) ON [PRIMARY]

Enter some data to the tables :

From the following pictures you can see some data in the table for C# - Crystal Reports tutorial
Order Master Table Data

Order Details Table Data

Product Table Data

A step by step tutorial for beginners who is creating their Crystal Reports for the first time in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
Here we are going to create a new Crystal Reports in C# from Product table in the above mentioned database crystalDB. The Product
Table has three fields (Product_id,Product_name,Product_price) and we are showing the whole data from Product table to the C# - Crystal
Reports project.
Open Visual Studio .NET and select a new CSharp Windows project.

Now you will get the default Form1.cs.


From the main menu in Visual Studio C# project select PROJECT-->Add New Item . Then Add New Item dialogue will appear and select
Crystal Reports from the dialogue box.

Select Report type from Crystal Reports gallery.


Accept the default settings and click OK.
Next step is to select the appropriate connection to your database (here crstaldb). Here we are going to select OLEDB Connection for
SQL Server to connect Crystal Reports in C#.
Select OLE DB (ADO) from Create New Connection .
Select Microsoft OLE DB Provider for SQL Server .

The next screen is the SQL Server authentication screen for connecting to the database - crystalDB. Select your Sql Server name , enter
userid , password and select your Database Name .
Click next , Then the screen shows OLE DB Property values , leave it as it is , and then click finish button.
After you click the finish button , the next window you will get your Server name under OLEDB Connection, from there selected database
name (Crystaldb) and click the tables , then you can see all your tables from your database.
From the tables list double click the Product table then you can see the Product table will come in the right side list.

Click Next Button


Select all fields from Product table to the right side list .
Click Finish Button. Then you can see the Crystal Reports designer window in your C# project. In the Crystal Reports designer window
you can see the selected fields from Product table. You can arrange the field Objects and design of the screen according your
requirements. After that your screen is look like the following picture.

Now the designing part is over and the next step is to call the Crystal Reports in your C# application and view it through Crystal Reports
Viewer control in C#.
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
After you drag the CrystalReportViewer to your form , it will look like the following picture.

You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.


using CrystalDecisions.CrystalReports.Engine;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

NOTES: 
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 

The Crystal Reports file path in your C# project file location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

When you run the source code you will get the report like the following picture. 

When you click the button, the application will ask the username and password. Later in this tutorial you can find how to avoid asking
username and password - C# Dynamic logon parameters in Crystal Reports. 

Hope this tutorial help you to create your first Crystal Reports in C#.

C# Crystal Reports from multiple tables

The following section describes how to create Crystal Report from multiple tables in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
Here we are going to generate Crystal Reports from multiple tables in C#. Here we have three tables (ordermaster , orderdetails and
product ) and we are generating a Crystal Report from these three tables by connecting each table with their related fields.
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
Hope you understand the basics of generating a Crystal Reports in C# , this section is the continuation of the first part, so here we avoid
some basic steps and start from the table selection of Crystal Reports.
Select all table from the table list to right side list box, because we are creating report from three tables ( OrderMaster, OrderDetails,
Product) . If you don't know up to this part of the tutorial , refer previous tutorial for up to selecting databese for Crystal reports.

The next step is to make relations between these selected tables. Here we are connecting the related fields from each table. For that we
arrange the tables in visible area in the list (this is not necessary ) and select the fields that we want to make relation and drag to the
related field of the other selected tables. After made the relations with tables the screen is look like the following picture .
Next step is to select the fields from the selected tables ( OrderMaster, OrderDetails, Product) . Here we are selecting the fields
Customername , orderdate from ordermastertable , Productname from product table and quantity from order details table. The field
selection screen is look like the following picture .
After select the fields from tables, click the Finish button because now we are not using any other functionalities of the Crystal Reports
wizard. After that you will get the Crystal Reports designer window . You can arrange the fields in the designer window according to your
requirement to view the report .
For re-arranging fields in the designer window , you can drag the field object on the screen . For editing right click the field object and
select Edit Text Object. The following picture shows the sample of designer window after rearrange the field.

Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .

After you drag the CrystalReportViewer to your form , it will look like the following picture.
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

NOTES: 
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 

The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

After you run the source code you will get the report like this. 
When you click the button, the application will ask the username and password. Later in this tutorial you can find how to avoid asking
username and password - C# Dynamic logon parameters in Crystal Reports.

C# Crystal Reports String parameter

The following section describes how to pass a String parameter to Crystal Reports from C# application.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
Here we pass a String parameter from C# to Crystal Reports . For example , from C# program we pass a customer name as a parameter
and show all the orders of that customer to the Crystal Reports.
In the previous tutorial we saw how to generate a C# - Crystal Reports from multiple tables. This program is the continuation of previous
tutorial , the only difference is that we pass a Customer Name as String parameter and get the report of that particular Customer only .
Before starting to this section just take a look at the previous section C# Crystal Reports from multiple tables.
In the previous section we are getting the report of all orders from all customers , that is , all orders placed by all customers . In this
section we pull out the selected customer report only by passing Customer name as argument.
Hope you understand the previous section well, if not, please click hereC# Crystal Reports from multiple tables.
Next step is to create a String parameter in Crystal report designer window .
Select the Field Explorer from CrystalReport Menu. (Up to here explained in detail in the previous section C# Crystal Reports from
multiple tables)

Then you can see Field Explorer in the Left hand side.
Select Parameter Field from Field Explorer and right Click on Parameter Field.

Fill the appropriate name for Name and Prompting text fields like the following picture.

After creating the parameter field , we have to create the selection formula for the Crystal Reports parameter.
For creating selection formula , Right click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA ->
RECORD .

Now you can see the record Selection Formula Editor Screen. For creating selection formula , you have to select the fields from above
field list and make the formula .
First you have to select OrderMaster.OrderMaster_customername from Report Field and select the comparison operator and select the
parameter field. Double click each field then it will be selected.
Form the following picture you can understand how to select fields.
You can close Selection Formula Editor screen after creating selection formula.
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .

You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.


using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");

ParameterFieldDefinitions crParameterFieldDefinitions ;
ParameterFieldDefinition crParameterFieldDefinition ;
ParameterValues crParameterValues = new ParameterValues();
ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

crParameterDiscreteValue.Value = textBox1.Text;
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition = crParameterFieldDefinitions["Customername"];
crParameterValues = crParameterFieldDefinition.CurrentValues;

crParameterValues.Clear();
crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();

}
}
}

NOTE : 
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 

The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

Now you can run the program . Enter a Customer Name(enter any existing customer from Ordermaster table) and click the button , then
your report is look like the following picture. 

Here we get the result of the Customer4's order details.

C# Crystal Reports Integer parameter

The following section describes the how to pass an Integer Parameter to Crystal Reports from C#
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In the previous tutorial , we already saw how to pass a String parameter to the Crystal Reports from C# - C# Crystal Reports String
Paramater - and get the result. This section is almost same as the previous section and the only difference is that instead of String
parameter here we pass an Integer parameter from C# . So before we start this section you can take look at the previous section C# Crystal
Reports String Paramater , it explain each steps in details with pictures.
When we pass an Integer parameter , we have to create a new Integer parameter in the Parameter Fields of Field Explorer. Then we will
get the following screen and fill the fields like in the following picture .

After creating the parameter field , we have to create the selection formula for the Crystal Reports . For creating selection formula , Right
click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA -> RECORD .
Then you can see the record Selection Formula Editor. You can make selection formula from this screen by choosing fields from the lists
in the selection formula editor screen.
Here only the Product table is selected for generating Crystal Reports . We are making a formula like select the records from Product table
whose value is greater than the input value. For that, first we select the table field that is Product_price from Product table and then we
select the comparison operator and finally we select our Parameter we created earlier. The following picture shows how to select fields
from lists . Double click each field then it will automatically selected .

You can close the Selection Formula Editor screen after creating the formula.
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project
using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");

ParameterFieldDefinitions crParameterFieldDefinitions ;
ParameterFieldDefinition crParameterFieldDefinition ;
ParameterValues crParameterValues = new ParameterValues();
ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

crParameterDiscreteValue.Value = Convert.ToInt32(textBox1.Text);
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition = crParameterFieldDefinitions["Price"];
crParameterValues = crParameterFieldDefinition.CurrentValues;

crParameterValues.Clear();
crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();

}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

Now you can run the program . Enter any price , then you can see the report of the Product list whose price is greater than or equal to the
entered price. 
The Crystal Reports showing the result of Product list whose price is greater than 50.

C# Crystal Reports Date parameter

The following section describes how to pass a Date parameter field from C# to Crystal Reports.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In the previous sections , we already saw how to pass a string parameter to Crystal Reports - C# Crystal Reports String Paramater, how to
pass an Integer parameter to Crystal Reports - C# Crystal Reports Integer Paramater and get the result. This section is very similar to the
previous two sections , so before we begin this section , take a look at the previous two sections.
C# Crystal Reports String Paramater
C# Crystal Reports Integer Paramater
When we pass a Date parameter from C# , we have to create a new date parameter in the Parameter Fields of Field Explorer. Then we will
get the following screen and fill the fields like in the picture .

After creating the date parameter field , we have to create the selection formula for the Crystal Reports . For creating selection formula ,
Right click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA -> RECORD .
Then you can see the record Selection Formula Editor. You can make selection formula from this screen by choosing fields from the lists
in the selection formula editor screen.
Here we have three tables selected for report (ordermaster , orderdetails and product ) and we are making the formula like , select all
records details from the tables whose order date is greater than the input date parameter. For doing this you have to select
Ordermaster.orderdate , a comparison operator and parameter date field from selection list of Formula Editor and make the formula. The
following picture shows how to select the fields from formula editor and make the formula. Double click each field then it will
automatically selected .

You can close Selection Formula Editor screen after creating the formula.
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");

ParameterFieldDefinitions crParameterFieldDefinitions ;
ParameterFieldDefinition crParameterFieldDefinition ;
ParameterValues crParameterValues = new ParameterValues();
ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

crParameterDiscreteValue.Value = textBox1.Text;
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition = crParameterFieldDefinitions["Orderdate"];
crParameterValues = crParameterFieldDefinition.CurrentValues;

crParameterValues.Clear();
crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

Now you can run the program . Enter any date , then you can see the report whose order date is greater than or equal to the entered date. 

Here we got the result of orders whose date is greater than the entered date

C# Crystal Reports Dynamic Logon parameters

The following section describes how to pass the logon information likeServer Name , database Name , User Name and
password dynamically to the Crystal Reports from C# applications.
When you run the previous programs in this C# tutorial , the Crystal Reports asks the Username and Password every time you run the
Crystal Report. This section explains how to avoid the dialogue box asking username and password at runtime on Crystal Reports login .
In this section we are passing User ID , Password , Server Name and Database Name dynamically to Crystal Reports from C# .
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In many situations dynamically passing the logon parameter fields are very useful , for example if you develop a database project in a test
server environment and later you have to migrate it to other server , in these situations it is better to give these information dynamically to
Crystal Reports .
In step by step tutorial for creating a Crystal Reports from C# - we created a report selecting all data from the Product table . There is no
chance to change the server name or any other information on runtime in that case, because it is a static report and it will asks username
and password every time you run the Crystal Reports . Here we are passing Server Name , UserID and Password dynamically to the
Crystal Reports from our C# program
Here we use Crystal Reports ConnectionInfo class for passing connection information.
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables ;

cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");

crConnectionInfo.ServerName = "YOUR SERVER NAME";


crConnectionInfo.DatabaseName = "YOUR DATABASE NAME";
crConnectionInfo.UserID = "YOUR DATABASE USERNAME";
crConnectionInfo.Password = "YOUR DATABASE PASSWORD";

CrTables = cryRpt.Database.Tables ;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

You have to replace the source code values of 

crConnectionInfo.ServerName = "YOUR SERVER NAME";


crConnectionInfo.DatabaseName = "YOUR DATABASE NAME";
crConnectionInfo.UserID = "YOUR DATABASE USERNAME";
crConnectionInfo.Password = "YOUR DATABASE PASSWORD";

with your real-time values . 


C# Crystal Reports Formula Field

The following C# - Crystal Reports section describes how to add a formula field in the Crystal Reports .
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
The situations when formula field is using :
If you have a Crystal Reports with Qty and Price fields and you need an additional field in your Crystal Reports for Total, that is TOTAL
= QTY X PRICE . In these types of situations you can use the Formula Field in Crystal Reports.
In this C# Crystal Reports tutorial we are showing that all orders with qty and price and the total of each row , that means each in each
row we are showing the total of qty and price.
Before starting this tutorial Create a new Crystal Reports with fields CustomerName , Order Date , Product Name and Product Price . If
you do not know how to create this report , just look the previous tutorial C# Crystal Reports from multiple tables . In that report selecting
only four fields , here we need one more field Product->Price and one formula field Total.
After you create the above Crystal Reports, your CR designer screen is look like the following picture :

Next step is to create a Formula Field for showing the result of Qty X Price .
Right Click the Formula Field in the Field Explorer and click New. Then you will get an Input Message Box , type Total in textbox and
click Use Editor.
Now you can see the Formula Editor screen . Here you can enter which formula you want . Here we want the result of Qty X Price . For
that we select OrderDetails.Qty , the multipy operator (*) and Product.Price . Double click each field for selection.

Now you can see Total Under the Formula Field . Drag the field in to the Crystal Reports where you want to display Total.

Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

When you run this program you will get your screen like the following picture. 

C# Crystal Reports Summary Field

The following C# - Crystal Reports section describes how to add a summary field in the Crystal Reports .
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
This section is the continuation of the previous tutorial C# Crystal Reports Formula Field . So before we start this tutorial , take a look at
the previous tutorial C# Crystal Reports Formula Field .
Hope you already gone through the previous section C# Crystal Reports Formula Field. Here in this section we are calculating the grand
total of the Formula Field - Total . The Total field is a Formula field, the result of qty X price .
In the Crystal Reports designer view window, right click on the Report Footer , just below the Total field and select Insert -> Summary .
Then you will get a screen , select the Total from the combo box and select Sum from next Combo Box , and summary location Grand
Total (Report Footer) . Click Ok button

Now you can see @Total is just below the Total field in the report Footer.

Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

When you run this program your screen will look like the following picture. 

C# Crystal Reports Export to Pdf

There are situations when we want to export Crystal reports to .pdf format programmatically. In these situations we can
use ExportOptions for export the Crystal Reports to .pdf format. Also we have to
setPdfRtfWordFormatOptions and ExportFormatType.PortableDocFormat. In the following example you can see how to export a
Crystal Reports as a PDF format file in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In this section we are using our earlier program step by step tutorial for creating a Crystal Reports from C# for pull data from database to
Crystal Reports . Before we start this section take a look at the step by step tutorial for creating a Crystal Reports from C# .
Here we are making a Crystal Report from Product table and export the report content to a PDF format file.
Select the default form (Form1.cs) you created in C# and drag two buttons (Button1, Button2 ) and a CrystalReportViewer control to your
form.
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
ReportDocument cryRpt;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}

private void button2_Click(object sender, EventArgs e)


{
try
{
ExportOptions CrExportOptions ;
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = "c:\\csharp.net-informations.pdf";
CrExportOptions = cryRpt.ExportOptions;
{
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
}
cryRpt.Export();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

When you run this program you will get the PDF file (csharp.net-informations.pdf) in your computer's C: 

C# Crystal Reports Export to Excel

There are situations when we want to export Crystal reports to .xls format programmatically in C#. In these situations we can
use ExportOptions for export the Crystal Reports to .xls format. Also we have to setExcelFormatOptions and ExportFormatType.Excel .
In the following example you can see how to export a Crystal Reports as a Excel format file.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In this section we are using our earlier program step by step tutorial for creating a Crystal Reports from C# for pull data from database to
Crystal Reports . Before we start this section take a look at the step by step tutorial for creating a Crystal Reports from C# .
Here we are generating a Crystal Report from Product table and export the report content to an Excel format file.
Select the default form (Form1.cs) you created in C# and drag two buttons (Button1, Button2 ) and a CrystalReportViewer control to your
form.
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
ReportDocument cryRpt;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}

private void button2_Click(object sender, EventArgs e)


{
try
{
ExportOptions CrExportOptions ;

DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();


ExcelFormatOptions CrFormatTypeOptions = new ExcelFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = "c:\\csharp.net-informations.xls";
CrExportOptions = cryRpt.ExportOptions;
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.Excel;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
cryRpt.Export();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

When you run this program you will get the Excel file (csharp.net-informations.xls) in your computer's C: 

Email Crystal Reports from C# Application

The following program describes how to email a Crystal Reports from C# .


All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
For email a Crystal Report from C# first we have to export the Crystal Reports in any of the File Format available in Crystal Reports and
then Email it.
In this section we use the previous tutorial C# Crystal Reports Export to PDF file . So before we start this section please take a look at the
tutorialC# Crystal Reports Export to PDF file.
After export the Crystal Reports as a PDF file format in your disk , the next step is to email that .pdf file . For that here we are
usingSystem.Web.Mail of C# . We have to provide the necessary information to configuring SmtpMail client and send the exported file as
attachment .
Select the default form (Form1.cs) you created in C# and drag two buttons (Button1, Button2 ) and a CrystalReportViewer control to your
form.
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Web.Mail
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Web.Mail;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
ReportDocument cryRpt;
string pdfFile = "c:\\csharp.net-informations.pdf";

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}

private void button2_Click(object sender, EventArgs e)


{
try
{
ExportOptions CrExportOptions ;
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = pdfFile;
CrExportOptions = cryRpt.ExportOptions;
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
cryRpt.Export();

sendmail();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void sendmail()


{
try {
SmtpMail.SmtpServer.Insert(0, "your hostname");
MailMessage Msg = new MailMessage();
Msg.To = "to address here";
Msg.From = "from address here";
Msg.Subject = "Crystal Report Attachment ";
Msg.Body = "Crystal Report Attachment ";
Msg.Attachments.Add(new MailAttachment(pdfFile));
System.Web.Mail.SmtpMail.Send(Msg);
}
catch (Exception ex) {
MessageBox.Show (ex.ToString());
}
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

Before you run this program , you have to provide the necessary SMTP information , that is your HOSTNAME , FROM ADDRESS and
TO ADDRESS to the SMTP client.

C# Crystal Reports without database

Usually we are using Crystal Reports to fetch data from databases and show it as a report. Here we are generating a Crystal Reports from
C# without using a database . For generating a Crystal Reports without database , here we are using a Strongly Typed Dataset and a Data
Table of C#.
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
Generating a Strongly Typed DataSet
Create a new C# Project and create a Dataset from Project - Add New Item Dialogue Box.

Select Dataset from list


Accept the default name DataSet1.xsd .
Create a data table for DataSet1.xsd in C#.
Select DataSet1.xsd from Solution Explorer and right click . Select datatable from the menu. Then you will get a datatable in the Datast .
Right click the datatable and select Add-Column .

Here we are making a two column Crystal Reports , so we need two column in the data table . Add and ID column and Item column in the
Data Table.

Now the dataset part is over . Next step is to create a Crystal Reports from the Dataset we created. Select a new Crystal Reports from Add
New Item menu and accept the default settings. The next screen is to select appropriate data source . There you can find the Datatable1
from Project data - ADO.NET Datasets , and select Datatable1 to the right side.
Click Next button and select ID and Item from the datatable1 to right side and click finish.

Now the C# Crystal Reports designer part is over . Next part is to create data for the Crystal Reports . For that we have to create a Data
Table through programmatically and add data to dataset1.
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
Copy and paste the following source code and run your C# project
using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;

namespace WindowsApplication1
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
DataSet1 ds = new DataSet1();
DataTable t = ds.Tables.Add("Items");
t.Columns.Add("id", Type.GetType("System.Int32"));
t.Columns.Add("Item", Type.GetType("System.String"));

DataRow r ;
int i = 0;
for (i = 0; i <= 9; i++)
{
r = t.NewRow();
r["id"] = i;
r["Item"] = "Item" + i;
t.Rows.Add(r);
}

CrystalReport1 objRpt = new CrystalReport1();


objRpt.SetDataSource(ds.Tables[1]);
crystalReportViewer1.ReportSource = objRpt;
crystalReportViewer1.Refresh();
}
}
}

C# Crystal Reports from SQL Query

The following section describes how to create a Crystal Reports in C# using SQL Query String .
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
Generating a Strongly Typed DataSet
Here we are using a Strongly Typed Dataset for generating a Crystal Reports from SQL Query string . Before start this section , you can
take look at the previous section of how to create a C# Crystal Report from Strongly Typed Dataset. Because here we are using Strongly
Typed Dataset for generating Crystal Report from SQL Query string.
Here we are generating a report against the Product table . So we are passing the following sql and generating the report
sql = "SELECT Product_id,Product_name,Product_price FROM Product";
Create a new C# project and create a new Strongly Typed Dataset fromProject - Add New Item Dialogue Box.
Add three column in the Strongly Typed Dataset .
Product_id
Product_name
Product_price
Create a new Crystal Report and select DataTable as Data Source . You can select DataTable from the wizard , Project Data - ADO.NET
Dataset - Crystal report Dataset1 - dataset1. Click the Next Button.

Select fields ( Product_id , Product_name , Product_price ) from the next screen and click the finish button. Then you will get the designer
screen with the selected fields. If you do not know how to create a dataset , refer the previous section How to create a C# Crystal Report
from Strongly Typed Dataset.
Now the designing part is over. From the source code we can pass the SQL source code to Crystal Reports.
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;
using System.Data.SqlClient ;

namespace WindowsApplication1
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
SqlConnection cnn ;
string connectionString = null;
string sql = null;

connectionString = "data source=SERVERNAME;initial catalog=DATABASENAME;user


id=USERNAME;password=PASSWORD;";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT Product_id,Product_name,Product_price FROM Product";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet1 ds = new DataSet1();
dscmd.Fill(ds, "Product");
MessageBox.Show (ds.Tables[1].Rows.Count.ToString());
cnn.Close();

CrystalReport1 objRpt = new CrystalReport1();


objRpt.SetDataSource(ds.Tables[1]);
crystalReportViewer1.ReportSource = objRpt;
crystalReportViewer1.Refresh();
}
}
}

connectionString = "data source=SERVERNAME;initial catalog=DATABASENAME;user id=USERNAME;password=PASSWORD;"; 


You have to provide the necessary database information to Connection String.

Dynamic Crystal Reports from C# Application

Usually Crystal Reports generating with pre-defined columns . That is, the fields showing in Crystal Reports are selecting through a
wizard at the time of Crystal Report design.
The following program describes how to generate a Crystal Report in C# with dynamic columns at the time of report generation . That is,
we are not selecting any column from database table at the time of Crystal Report design. Instead of that we are passing an SQl
query string and get the Crystal Report dynamically at runtime in C# . From the following picture you can understand how it works.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
Here we are going to create a Dynamic Crystal Report with the help of Strongly Typed Dataset. Create a new CSharp project and add a
Strongly Typed Dataset in the C# Project . Before creating a Strongly Typed Dataset take a look at the detailed tutorial of how to create
a C# Crystal Report from Strongly Typed Dataset of previous section .
Hope you understand how to create a C# Crystal Report from Strongly Typed Dataset. Create a new C# project and add a Strongly Typed
Datset . Add five columns in the DataTable of Strongly Typed Dataset. Here we are limiting as five column , but you can add any number
of column according to your reports requirements.

Next step is to create a Crystal Reports design from the Strongly Typed dataset. You have to add a Crystal Report in your project and
select data source as Strongly Typed Dataset. If you don't know how to do this section , refer the previous section of How to create a C#
Crystal Report from Strongly Typed Dataset.
Select all the column (five) from Strongly Typed Dataset .

Click finish button . Then you can see the selected fields in the Crystal Repots . Arrange the fields according to your requirement . Now
the designing part is over and the next step is to call the Crystal Reports in CSharp and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in CSharp and drag a Textbox , button and CrystalReportViewer control to your form (like
in the first picture ).
Here we are going to pass the SQl statements to Crystal Reports at runtime from C# program . For that we have to parse the SQL
statement before we passing it to Crystal Reports. So we create a function for parsing SQL statements in the C# program.
Public Function procesSQL() As String
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;
using System.Data.SqlClient ;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
CrystalReport1 objRpt = new CrystalReport1();

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
SqlConnection cnn ;
string connectionString = null;
string sql = null;
connectionString = "data source=SERVER NAME;initial catalog=crystaldb;user id=USER NAME;password=PASSWORD;";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = procesSQL();
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet1 ds = new DataSet1();
dscmd.Fill(ds, "Product");
objRpt.SetDataSource(ds.Tables[1]);
crystalReportViewer1.ReportSource = objRpt;
crystalReportViewer1.Refresh();
}

public string procesSQL()


{
string sql = null;
string inSql = null;
string firstPart = null;
string lastPart = null;
int selectStart = 0;
int fromStart = 0;
string[] fields = null;
string[] sep = { "," };
int i = 0;
TextObject MyText ;

inSql = textBox1.Text;
inSql = inSql.ToUpper();

selectStart = inSql.IndexOf("SELECT");
fromStart = inSql.IndexOf("FROM");
selectStart = selectStart + 6;
firstPart = inSql.Substring(selectStart, (fromStart - selectStart));
lastPart = inSql.Substring(fromStart, inSql.Length - fromStart);

fields = firstPart.Split(',');
firstPart = "";
for (i = 0; i <= fields.Length - 1; i++)
{
if (i > 0)
{
firstPart = firstPart + ", " + fields[i].ToString() + " AS COLUMN" + (i + 1);
firstPart.Trim();

MyText = (TextObject) objRpt.ReportDefinition.ReportObjects[i+1];


MyText.Text = fields[i].ToString();
}
else
{
firstPart = firstPart + fields[i].ToString() + " AS COLUMN" + (i + 1);
firstPart.Trim();

MyText = (TextObject)objRpt.ReportDefinition.ReportObjects[i+1];
MyText.Text = fields[i].ToString();
}
}
sql = "SELECT " + firstPart + " " + lastPart;
return sql;
}
}
}

connectionString = "data source=SERVER NAME;initial catalog=crystaldb;user id=USER NAME;password=PASSWORD;"; 


You have to provide the necessary database information to Connection String.

C# Crystal Reports from XML

Usually we are generating Crystal Reports from Databases , here in the following section describes how to create a Crystal reports
from XML file in C#. This is very similar to creating Crystal Reports from database , the only difference is that you have to select the data
source as the XML file at the designing time of Crystal Report in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In order to generating Crystal Report from XML file , we have to create an XML file . Here we are going to create an XML file and name
it asProduct.XML . The structure of the Product.XML file is same as the Product table in the crystaldb database earlier mentioned in this
sectionC# crystaldb . The content of the product.xml is shown below.
Download Product.XML
Generating Crystal Report from XML file is very similar to generating Crystal Report from Databases. The only difference is happened
when you selecting the datasource part. Here you have to select Create New Connection - Database Files and select the XML file you
want to generate Crystal Reports (In this case you select the Product.xml ).
Select all the fields from Product and click finish button
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

NOTES: 
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 

The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt

C# Crystal Reports - sub reports

The following progrm describes how to create a sub report within a Crystal Report in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
Subreport in Crystal Reports means that a report inside a Crystal Report . When we want to show some additional information about a
data field in a Crystal Reports row, we use the subreports features to show the details. We can display sub report in two ways , one is to
show subreport directly under the main row details. The other method is to show it as C# Crystal Reports on demand sub-reports , that
means we put an Hyper link just below the row filed , and when the user click that hyper link it will show the subreport.
In this section we are going to generate a sub-report under the main row details. That is for each row there is a subreoprt for the details.
Here we are going create an order report based on three tables in the database and show a subreoprt for each row field of Product Name.
Here we are using our earlier program C# Crystal Reports from multiple tablesto show the main Crystal Reports Data , so refer C# Crystal
Reports from multiple tables , before start this section .
Create a Crystal Reports using three tables and select customername , date , product and qty . It will explain in detail the previous
section C# Crystal Reports from multiple tables.
Next step is to create a sub report inside the main report. Here we are showing the Product details in each row of the specified product in
the main row.
After create the main report , right click on Crystal Reports designer window and select Insert-Subreport.

Then you will get the subreport object , drag the object in the designer window at the down part of the details tab , just below the fields in
the details tab. When you release the mouse you will get a dialogue box asking report name . Enter a report name , and click the Report
Wizard Button .
The wizard shows the table selection screen and select the table . Here in this case we have to select the Product Table from the list and
click next .
Next screen is showing the table , from there select the fields you want to show the data and click finish. The you will get the sub report
main screen again and select Link tab .
The link tab is making relation with your main Report and subreport . Here we are linking the productname from main report to the
subreport. For that select Product.Product_name from Available fields.
Accept the other settings as it is in the screen and click ok. Now you can see the sub report object in the screen , if you want to re-arrange
subreport design , double click on subreport object then you can design subreport.

Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

C# Crystal Reports - on demand sub reports

The following program shows how to create a Crystal Report On Demand Subreport in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In the previous section of C# Crystal Reports sub-reports is described how to insert a subreport in Crystal Reports . In the previous section
the sub report is displayed directly under each row details of main report .
The following section explains how to display subreport when the user click in a hyper link in the main Crystal Report . In this case the
sub report has only a link to the main Report . That is when the user click the link , then only the subreport display , it is called On
Demand Report .

This section is the continuation of the previous section C# Crystal Reports sub-reports. Here we are creating a Sub report in Crystal
Report and make a link in the main Crystal Reports for on-demand subreport.
Select the subreport object in the Crystal Reports and right click , then select Format Object .
Then you will get the Format Editor . Select Sub report tab from Format Editor , you can find there a check box - On-demand
Subreport . You have to select that check box , then the sub report become as a link in your main Crystal Reports. If you want to change
the title , you can change it in subreport name textbox. Finally click OK button.

Now the designing part is over and the next step is to call the Crystal Reports in CSharp and view it in Crystal Reports Viewer control .
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

C# Crystal Reports - Date to Date

The following program describes how to generate a Date to Date report from Crystal Reports in C#
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In the previous sections explains How to pass C# Crystal Reports Date Paramater and also explain C# Dynamic logon parameters in
Crystal Reports. So before we start this section take a look at the previous sections because we are here using sections from these tutorial.
Hope you understand the previous two sections well (1 - C# Crystal Reports Date Paramater, 2 - C# Dynamic logon parameters in Crystal
Reports). Here we are creating two date parameter and pass it to Crystal Report at run time also the Crystal Report using dynamic logon
parameter to access database.
Createting two date parameters (dateFrom and dateTo).
Date From parameter.

Date To Parameter
Here we have three tables selected for report (ordermaster , orderdetails and product ) and we are making the formula like , select all
records from the tables whose order date is between fromDate parameter and toDate paramater . For doing this you have to select from
date as Ordermaster.orderdate, to date as Ordermaster.orderdate , comparison operators , boolean operator (AND) and date parameters
fromdate and todate fields from selection list of Formula Editor and make the formula.
The following picture shows how to select the fields from formula editor and make the formula. Double click each field then it will
automatically selected .

After the creation of selection formula you can close that screen .
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in CSharp and drag two Textboxs (from date entry and to date entry) , a button and
CrystalReportViewer control to your form.
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");

TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();


TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;

ParameterFieldDefinitions crParameterFieldDefinitions ;
ParameterFieldDefinition crParameterFieldDefinition ;
ParameterValues crParameterValues = new ParameterValues();
ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

crParameterDiscreteValue.Value = textBox1.Text;
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition = crParameterFieldDefinitions["fromDate"];
crParameterValues = crParameterFieldDefinition.CurrentValues;

crParameterValues.Clear();
crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

crParameterDiscreteValue.Value = textBox2.Text;
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition = crParameterFieldDefinitions["toDate"];
crParameterValues = crParameterFieldDefinition.CurrentValues;

crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

crConnectionInfo.ServerName = "YOUR SERVERNAME";


crConnectionInfo.DatabaseName = "DATABASE NAME";
crConnectionInfo.UserID = "USERID";
crConnectionInfo.Password = "PASSWORD";

CrTables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}

crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 

crConnectionInfo.ServerName = "YOUR SERVERNAME";


crConnectionInfo.DatabaseName = "DATABASE NAME";
crConnectionInfo.UserID = "USERID";
crConnectionInfo.Password = "PASSWORD";

You have to pass the necessary database connection information. 

Now you can run the program . Enter from date and to date , then you can see the report whose order date is between from date and to date
you passed to Crystal reports. 

How to print Crystal Reports in C#

The following program shows how to print multiple copies of Crystal reports from C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please
take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
The following program generate a Crystal Reports from product table and print 2 copies of report without using CrystalReportViewer in
C#. The program generate report from Product table , the step by step tutorial for creating a Crystal Reports from C# section explains how
to create report from Product table. Also the program dynamically passing the logon parameters to Crystal Report. If you don't know how
to pass dynamic logon parameter please take a look at the section C# Dynamic logon parameters in Crystal Reports.
Hope you understand the previous section well. Create a Crystal report from Product Table and copy and paste the following source code
in the project.
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");

TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();


TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;

crConnectionInfo.ServerName = "YOUR SERVERNAME";


crConnectionInfo.DatabaseName = "DATABASE NAME";
crConnectionInfo.UserID = "USERID";
crConnectionInfo.Password = "PASSWORD";

CrTables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}

cryRpt.Refresh();
cryRpt.PrintToPrinter(2, true, 1, 2);

}
}
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 


The Crystal Reports file path in your project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal
Reports file like c:\projects\crystalreports\CrystalReport1.rpt 
crConnectionInfo.ServerName = "YOUR SERVERNAME";
crConnectionInfo.DatabaseName = "DATABASE NAME";
crConnectionInfo.UserID = "USERID";
crConnectionInfo.Password = "PASSWORD";

You have to pass the necessary database connection information. 

Now you can run the program . When you run this program the program will print multiple copies of Crystal Reports.

How to deploy Crystal Report

The following section describes how to deploy a Crystal Reports components and assemblies on the target machine.
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
Crystal Reports for Visual Studio ships with your deployment projects that enable you to deploy Crystal Reports components and
assemblies on the target machine. We can use different approaches to install Crystal Reports runtime files on the target machine in order
to run your C# applications smoothly.
If you are using Visual Studio then during your setup and deployment you can add the CRRedist2005_x86.msi file to your setup file and
distribute it as a single setup file with your C# application. The installer can execute the setup file automatically within your .Net Project
in a single click. You can find the CRRedist2005_x86.msi file in your system's C:\Program Files\Microsoft Visual Studio
8\SDK\v2.0\BootStrapper\Packages\CrystalReports . Also you can distribute the CRRedist2005_x86.msi separately and install it on the
target machine where your C# applications installed.
The other way to install Crystal Reports on target machine is to create a setup file using Merge Modules and distribute it with your C#
application or as a separate setup file. Click the following link to see how to make a setup file with Merge Modules.
C# Crystal Reports installer using Merge Modules.

How to Crystal Report Merge Module

The following section shows how to create a setup file for Crystal Reports Client side installations using Merge Modules.
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step
tutorial for creating a Crystal Reports from C#.
In the previous section How to install C# Crystal Reports on Clinet machine , we already saw how to deploy a Crystal Reports
components and assemblies on the target machine using CRRedist2005_x86.msi file. Here we are creating a separate setup file for client
side installations using Crystal Report Merge Modules.
Crystal Reports uses merge modules to ensure the correct report components and assemblies are installed with your deployment of C#
project. A merge module is a set of components that are merged with a Windows installer for applications that need them. The following
steps are creating a setup file for Crystal Reports Client side installation using Merge Modules.
Before creating a setup project, make sure that the following files exist in the \Program Files\Common Files\Merge Modules folder.
CrystalReportsRedist2005_x86.msm
Microsoft_VC80_ATL_x86.msm
policy_8_0_Microsoft_VC80_ATL_x86.msm
Steps to create Setup file for your C# Application.
1) Make sure the above mentioned files are in the \Program Files\Common Files\Merge Modules folder , If the files are not there you can
download the file and copy it to the folder \Program Files\Common Files\Merge Modules .
Download: https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/11688
2) Open your Visual Studio
3) Select "New Project" from File menu.

4) Select "Setup and Deployment" from "Other Project Types"


5) In the "Solution Explorer", select your setup project, right-click, and select Add and Merge Module from the menu.
6) Select CrystalReportsRedist2005_x86.msm to your setup project.
The file available at \Program Files\Common Files\Merge Modules

Then you can see Microsoft_VC80_ATL_x86.msm and policy_8_0_Microsoft_VC80_ATL_x86.msm will be automatically added in the


Detected Decencies section.
7) Build your project.
Now you will get the setup file for distribution. Either you can add this setup file to your C# application installer or distribute it as a
separate setup file.

5 Tests for Top Performance by Jason Dove

Summary: How to improve the efficiency of any Crystal Report using one or more of the five steps in this article.
5 Tests for Top Performance
It is complete, your masterpiece report. Not only does it meet your customer's expectations, it blows them out the water, all they want is
beautifully summarised and displayed in a myriad of ways.
Then
Disaster!
You try to run the report for a month against the live database and not the two days test data you used for development.
Suddenly your report's runtime goes from twenty seconds to two hours.
Every Crystal Reports developer has experienced this situation and it can be one of the most frustrating aspects of report design.
Thankfully there are a variety of things that can be done to combat bad performance, any one of which can reap huge benefits.
Here are the five most likely causes of poor performance and how to mitigate their effects.
1. The Database Set Up
This may or may not be within your direct control to alter, but databases are not set up ideally.
Two top contenders are:
a: The fields you are filtering on are not indexed. You can check whether or not this is the case by referring to the Linking Tab in the
Database Expert window. Indexed fields have colored markers next to them.
I have personally seen reports run hundreds of times quicker due to the addition of an index being added to an important (to the report
filter) field.
b: Using a view rather than a table to report from can be devastating to a report's performance. This is mainly due to views not having
indexes. A view is a collection of tables (much like a basic report) and is often used to simplify data for end users.
The only way to avoid this is to report on the tables which make up the view. Identifying whether the source of a field is a table or a view
can be done via the Database Expert as tables and views are listed separately.
Identifying which tables make up a view can be much trickier and you may need the help of the database documentation.
Also, when using Oracle databases, turning off the case sensitive option on queries can really speed up reporting times but may require
existing reports to be rewritten.
2.Using the wrong ODBC driver.
ODBC drivers are how Crystal Reports attaches to the database. There is usually a variety of ODBC drivers which will work for any
particular make of database and some are better than others.
The only way to really test this is to run the report with all the suitable ODBC drivers and see which is the most efficient.
Experience has taught me that the ODBC driver provided with the software associated to the database is usually the best option.
3.Excessive Use of Sub Reports
Each sub report is like another report accessing the database, and if that sub report is placed in the Detail Section it will run for EVERY
record the main report loads. Even if placed in a Group Section the sub report will still be run numerous times.
Report Sections are usually the ideal place to home a sub report as they will only run once. But this still turns one report into two as far as
performance is concerned.
The best way to negate the performance issue caused by sub reports is to not use them.
Ninety nine percent of sub reports are not necessary and the same result can be achieved using other methods through grouping, running
totals and / or formulas.
4.Table Linking
Anything other than a Link Type of equals ('=') will cause a massive degradation in performance.
The Link Options window (accessible through right clicking on a specific link) will allow any values to be reset.
If there is a need for this time of link, the same result can be achieved through the Group Selection or through formatting (and hiding the
unwanted records) once they are loaded into the report.
5. Record Selection
When code for the record selection is written correctly, Crystal Reports will pass all the logic to the database as SQL and only return the
data needed.
If the record selection is not written in an SQL friendly way, Crystal Reports will bring back all the data and then filter it locally. This can
be drastically slower than when calculated on the database.
Using the Record Selector Expert will guarantee that any filter created will be evaluated on the database and be as efficient as possible.
An additional point which can make a difference in some cases is when the report is scheduled to run. Heavy network traffic or database
usage can impact a report's running time.
Working through the above points will enhance the efficiency of your slowly running reports. Building your reports with all this in mind
from the beginning will save you redevelopment time later.

C# Excel Tutorial

Automation of an Excel file allows us to doing various operations from C#. We can automate an Excel file from C# in two ways.
Using Excel Object Model in one way and another way is using Microsoft Jet Engine to connect Excel from CSharp. Through the
automation from C# we can achieve creating a new workbook, adding data to a workbook, creating charts etc.
How to automate Microsoft Excel from Microsoft Visual C#.NET ?

C# Excel Interop
From the following links you can see helpful resources about Excel automation from C#.

How to create Excel file in C#

The following section explains how to create an Excel file programmatically using C#.
Before you create an Excel file in C# , you have to add the Microsoft Excel 12.0 Object Library to you project.
Create a new project and add a Command Button to the Form.
Form the following pictures you can find how to add Excel reference library in your project.
Select reference dialogue from Project menu

Select Microsoft Excel 12.0 Object Library and click OK button


Copy and paste the following source code in your C# project file.

using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,


Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.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();
}
}
}
}

Note : You have to add Microsoft.Office.Interop.Excel to your source code. 


using Excel = Microsoft.Office.Interop.Excel; 

When you execute this program , it will create an excel file in you c: 

How to open an Excel file in C#

The following section explains how to open and read an Excel file through C#.
For open or read an Excel file in C# , first you have to add the Microsoft Excel 12.0 Object Library in you project.
Create a new project and add a Command Button to the Form.
Form the following images you can find how to add Excel reference library in your project.
Select Reference Dialogue from Project menu

Select Microsoft Excel 12.0 Object Library and click OK button


Copy and paste the following source code in your C# project file.

using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

MessageBox.Show(xlWorkSheet.get_Range("A1","A1").Value2.ToString());

xlWorkBook.Close(true, misValue, misValue);


xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}

Note : You have to add Microsoft.Office.Interop.Excel to your source code. 


using Excel = Microsoft.Office.Interop.Excel; 

When you execute the C# source code , it will open the excel file and read the content in the cell A1

How to read an Excel file in C#

From the following section you can see How to find the last row data in Excel worksheet or How to find the Used area in an Excel
worksheet from C#.
The following C# source code using Microsoft Excel 12.0 Object Libraryfor reading an Excel file. In the previous section we saw how
to import Microsoft Excel 12.0 Object Library in the CSharp project .
Create Excel file from CSharp
For reading entire content of an Excel file in C#, we have to know how many cells used in the Excel file. In order to find the used range
we use "UsedRange" property of xlWorkSheet . It will return the last cell of used area.
Excel.Range range ;
range = xlWorkSheet.UsedRange;
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range range ;

string str;
int rCnt = 0;
int cCnt = 0;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

range = xlWorkSheet.UsedRange;

for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)


{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
MessageBox.Show(str);
}
}

xlWorkBook.Close(true, null, null);


xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}

private void releaseObject(object obj)


{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}

}
}

When you execute this C# source code the program read all used cells from Excel file. 

How to format an Excel file using C#

The following section shows how to format an Excel file from C# .


The following source code using Microsoft Excel 12.0 Object Library .In the previous section we saw how to import Microsoft Excel
12.0 Object Library in the C# project .
Create Excel file from CSharp
Here we creating a mark list in Excel file and format the file from C# . First we MERGE excel cell and create the heading , then the
students name and totals make as BOLD . And finally create a border for the whole marklist part.
After you execute the source code you will get an Excel file, its look like in the following picture .
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
Excel.Range chartRange ;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

//add data
xlWorkSheet.Cells[4, 2] = "";
xlWorkSheet.Cells[4, 3] = "Student1";
xlWorkSheet.Cells[4, 4] = "Student2";
xlWorkSheet.Cells[4, 5] = "Student3";

xlWorkSheet.Cells[5, 2] = "Term1";
xlWorkSheet.Cells[5, 3] = "80";
xlWorkSheet.Cells[5, 4] = "65";
xlWorkSheet.Cells[5, 5] = "45";

xlWorkSheet.Cells[6, 2] = "Term2";
xlWorkSheet.Cells[6, 3] = "78";
xlWorkSheet.Cells[6, 4] = "72";
xlWorkSheet.Cells[6, 5] = "60";

xlWorkSheet.Cells[7, 2] = "Term3";
xlWorkSheet.Cells[7, 3] = "82";
xlWorkSheet.Cells[7, 4] = "80";
xlWorkSheet.Cells[7, 5] = "65";

xlWorkSheet.Cells[8, 2] = "Term4";
xlWorkSheet.Cells[8, 3] = "75";
xlWorkSheet.Cells[8, 4] = "82";
xlWorkSheet.Cells[8, 5] = "68";

xlWorkSheet.Cells[9, 2] = "Total";
xlWorkSheet.Cells[9, 3] = "315";
xlWorkSheet.Cells[9, 4] = "299";
xlWorkSheet.Cells[9, 5] = "238";

xlWorkSheet.get_Range("b2", "e3").Merge(false);

chartRange = xlWorkSheet.get_Range("b2", "e3");


chartRange.FormulaR1C1 = "MARK LIST";
chartRange.HorizontalAlignment = 3;
chartRange.VerticalAlignment = 3;

chartRange = xlWorkSheet.get_Range("b4", "e4");


chartRange.Font.Bold = true;
chartRange = xlWorkSheet.get_Range("b9", "e9");
chartRange.Font.Bold = true;

chartRange = xlWorkSheet.get_Range("b2", "e9");


chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium,
Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);

MessageBox.Show ("File created !");


}

private void releaseObject(object obj)


{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}

}
}

How to insert a picture in excel from C# App

The following section shows how to insert a picture in an Excel file from C# Application .
The following C# source code using Microsoft Excel 12.0 Object Library.In the previous section we saw how to import Microsoft Excel
12.0 Object Library in the C# project .
Create Excel file from CSharp
For inserting a picture in an Excel file from C# we have to call theAddPicture method. The parameters we have to pass like PictureName
with path , Left , Top , Width and Height.
After you execute the C# source code you will get the Excel file like the following picture.

using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

//add some text


xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File";

xlWorkSheet.Shapes.AddPicture("C:\\csharp-xl-picture.JPG", Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45);

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);

MessageBox.Show ("File created !");


}

private void releaseObject(object obj)


{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}

}
}

How to insert a background picture in excel

The following C# program shows , how to insert a background picture in Excel .


The following C# source code using Microsoft Excel 12.0 Object Library.In the previous section we saw how to import Microsoft Excel
12.0 Object Library in the C# project .
Create Excel file from CSharp
For inserting a background picture in Excel from C# we have to call the SetBackgroundPicture method of worksheet .
Syntax : SetBackgroundPicture(string filename)
Filename : The background picture filename .
After you execute the C# source code you will get the Excel file like the following picture.
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

xlWorkSheet.SetBackgroundPicture("C:\\csharp-xl-picture.JPG");

//add some text


xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkSheet.Cells[2, 1] = "Adding background in Excel File";

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);

MessageBox.Show ("File created !");


}

private void releaseObject(object obj)


{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}

}
}

How to create Excel Chart from C#

We can create Chart in Excel through C# . The following section shows how to create a Chart in Excel through C# source code .
The following C# source code using Microsoft Excel 12.0 Object Library.In the previous section we saw how to import Microsoft Excel
12.0 Object Library in the C# project .
Create Excel file from CSharp
Before we crating a Chart , we have to fill data in Excel sheet. Here we are filling the data in excel sheet through C# program. After fill
the data in your Excel sheet its look like the following picture.

After fill the data , We have to create a chart object in C# and configure the Chart object with necessary data like positions , size , data
range , chart type etc..
The following picture shows the excel file after created a chart.
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

//add data
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "Student1";
xlWorkSheet.Cells[1, 3] = "Student2";
xlWorkSheet.Cells[1, 4] = "Student3";

xlWorkSheet.Cells[2, 1] = "Term1";
xlWorkSheet.Cells[2, 2] = "80";
xlWorkSheet.Cells[2, 3] = "65";
xlWorkSheet.Cells[2, 4] = "45";

xlWorkSheet.Cells[3, 1] = "Term2";
xlWorkSheet.Cells[3, 2] = "78";
xlWorkSheet.Cells[3, 3] = "72";
xlWorkSheet.Cells[3, 4] = "60";

xlWorkSheet.Cells[4, 1] = "Term3";
xlWorkSheet.Cells[4, 2] = "82";
xlWorkSheet.Cells[4, 3] = "80";
xlWorkSheet.Cells[4, 4] = "65";

xlWorkSheet.Cells[5, 1] = "Term4";
xlWorkSheet.Cells[5, 2] = "75";
xlWorkSheet.Cells[5, 3] = "82";
xlWorkSheet.Cells[5, 4] = "68";

Excel.Range chartRange ;

Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);


Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;

chartRange = xlWorkSheet.get_Range("A1", "d5");


chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.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();
}
}

}
}

How to export excel chart from C#

The following C# program shows how to Export a Chart from Excel file to a Picture file like , BMP , JPG , GIF etc .
The following C# source code using Microsoft Excel 12.0 Object Library.In the previous section we saw how to import Microsoft Excel
12.0 Object Library in the C# project .
Create Excel file from CSharp
Before we crating a Chart , we have to fill data in Excel sheet. Here we are filling the data in excel sheet through CSharp program. After
fill the data in your Excel sheet its look like the following picture.

After fill the data in excel file, We have to create a chart object in CSharp and configure the Chart object with necessary data like
positions , size , data range , chart type etc.. and use the command for export chart as picture file .
chartPage.Export(@"C:\excel_chart_export.bmp","BMP",null );
The following picture shows the BMP Chart file export from Excel.
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

//add data
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "Student1";
xlWorkSheet.Cells[1, 3] = "Student2";
xlWorkSheet.Cells[1, 4] = "Student3";

xlWorkSheet.Cells[2, 1] = "Term1";
xlWorkSheet.Cells[2, 2] = "80";
xlWorkSheet.Cells[2, 3] = "65";
xlWorkSheet.Cells[2, 4] = "45";

xlWorkSheet.Cells[3, 1] = "Term2";
xlWorkSheet.Cells[3, 2] = "78";
xlWorkSheet.Cells[3, 3] = "72";
xlWorkSheet.Cells[3, 4] = "60";
xlWorkSheet.Cells[4, 1] = "Term3";
xlWorkSheet.Cells[4, 2] = "82";
xlWorkSheet.Cells[4, 3] = "80";
xlWorkSheet.Cells[4, 4] = "65";

xlWorkSheet.Cells[5, 1] = "Term4";
xlWorkSheet.Cells[5, 2] = "75";
xlWorkSheet.Cells[5, 3] = "82";
xlWorkSheet.Cells[5, 4] = "68";

Excel.Range chartRange ;

Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);


Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;

chartRange = xlWorkSheet.get_Range("A1", "d5");


chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;

//export chart as picture file


chartPage.Export(@"C:\excel_chart_export.bmp","BMP",misValue );

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.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();
}
}

}
}

How to excel chart in C# picturebox

The following C# program shows , how to get the Excel chart image in a Picture Box .
The following C# source code using Microsoft Excel 12.0 Object Library.In the previous section we saw how to import Microsoft Excel
12.0 Object Library in the CSharp project .
Create Excel file from CSharp
Before we crating a Chart , we have to fill the data in Excel sheet. Here we are filling the data in excel sheet through CSharp program.
After fill the data in your Excel sheet its look like the following picture.

After fill the data in excel sheet through CSharp program , We have to create a chart object through C# program and configure the Chart
object with necessary data like positions , size , data range , chart type etc.and use the command for export chart as picture file , then load
the picture from the path to picture box
chartPage.Export(@"C:\excel_chart_export.bmp", "BMP", misValue);
pictureBox1.Image = new Bitmap(@"C:\excel_chart_export.bmp");
The following picture shows the program screen after drawing the picture

using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

//add data
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "Student1";
xlWorkSheet.Cells[1, 3] = "Student2";
xlWorkSheet.Cells[1, 4] = "Student3";

xlWorkSheet.Cells[2, 1] = "Term1";
xlWorkSheet.Cells[2, 2] = "80";
xlWorkSheet.Cells[2, 3] = "65";
xlWorkSheet.Cells[2, 4] = "45";

xlWorkSheet.Cells[3, 1] = "Term2";
xlWorkSheet.Cells[3, 2] = "78";
xlWorkSheet.Cells[3, 3] = "72";
xlWorkSheet.Cells[3, 4] = "60";

xlWorkSheet.Cells[4, 1] = "Term3";
xlWorkSheet.Cells[4, 2] = "82";
xlWorkSheet.Cells[4, 3] = "80";
xlWorkSheet.Cells[4, 4] = "65";

xlWorkSheet.Cells[5, 1] = "Term4";
xlWorkSheet.Cells[5, 2] = "75";
xlWorkSheet.Cells[5, 3] = "82";
xlWorkSheet.Cells[5, 4] = "68";

Excel.Range chartRange ;

Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);


Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;

chartRange = xlWorkSheet.get_Range("A1", "d5");


chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;

//export chart as picture file


chartPage.Export(@"C:\excel_chart_export.bmp", "BMP", misValue);
//load picture to picturebox
pictureBox1.Image = new Bitmap(@"C:\excel_chart_export.bmp");

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.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();
}
}

}
}

C# data validation input box in excel file

The following C# program shows how to embedded a Data Validation Input Messages in an Excel file programmatically.
The following C# source code using Microsoft Excel 12.0 Object Library.In the previous section we saw how to import Microsoft Excel
12.0 Object Library in the C# project .
Create Excel file from CSharp
Data Validation Input Messages is using to embed a message in cells in an Excel Spread Sheet. When we select that cell the message will
display . It is very useful for data entry purpose for define the rules for entering data and also we can put a notes about the data in the cell.
The following image shows how a Data Validation Input Message after embedded in an Excel cell.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range chartRange ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

chartRange = xlWorkSheet.get_Range ("b2", "e9");


xlWorkSheet.get_Range("B5", "D5").Validation.Add(Excel.XlDVType.xlValidateInputOnly,
Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, misValue, misValue);
xlWorkSheet.get_Range("B5", "D5").Validation.IgnoreBlank = true;
xlWorkSheet.get_Range("B5", "B5").FormulaR1C1 = "Click Here to see Notes";
xlWorkSheet.get_Range("B5", "D5").Validation.InputTitle = "csharp.net-informations.com";
xlWorkSheet.get_Range("B5", "D5").Validation.ErrorTitle = "Error in Title";
xlWorkSheet.get_Range("B5", "D5").Validation.InputMessage = "Here is the notes embeded - you can enter 255 characters
maximum in notes ";
xlWorkSheet.get_Range("B5", "D5").Validation.ErrorMessage = "Error in Notes";
xlWorkSheet.get_Range("B5", "D5").Validation.ShowInput = true;
xlWorkSheet.get_Range("B5", "D5").Validation.ShowError = true;

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.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();
}
}

}
}

How to read from an Excel file using OLEDB

In the previous examples we used Microsoft Excel 12.0 Object Libraryfor read or write to and Excel file . In C# without using Excel
Object we can insert , edit , delete , select etc. in cell content of an Excel file usingOLEDB .
Here we are using OleDbConnection , OleDbDataAdapter , DataSet for doing these operations in an Excel file. You have to
import System.Datain the project for doing these operations . For read the content from an Excel file using ADO.NET , We can use the
SELECT command like in SQL Operations.
sample Select sql
sql = "select * from [Sheet1$]"
Here is the sample Excel file .
Open the connection using OLEDB Provider
(provider=Microsoft.Jet.OLEDB.4.0;Data Source='Your Filename';Extended Properties=Excel 8.0;)
Specify which data you want to read
select * from [Sheet1$]
Here is the screen short after reading from Excel file in C# .

using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.DataSet DtSet ;
System.Data.OleDb.OleDbDataAdapter MyCommand ;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-
informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to insert data to Excel file using OLEDB

In the previous examples we used Microsoft Excel 12.0 Object Libraryfor read or write to and Excel file . In C# without using Excel
Object we can insert , edit , delete , select etc. in cell content of an Excel file using OLEDB .
You have to import System.Data in the project for doing these operations . For add new content in the cell or insert a new content , We
can use the INSERT command like in SQL Operations.
sample UPDATE sql
sql = "Insert into [Sheet1$] (id,name) values('5','e')"
The following picture shows before and after update of the Sheet.

using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-
informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to update data in Excel file using OLEDB

In the previous examples we used Microsoft Excel 12.0 Object Libraryfor read or write to and Excel file . In C# without using Excel
Object we can insert , edit , delete , select etc. in cell content of an Excel file using OLEDB .
Here we are using OleDbConnection , OleDbDataAdapter , DataSet for doing these operations in an Excel file. You have to import
System.Data in the project for doing these operations . For update the content in the cell or modify the content in a cell , We can use the
UPDATE command like in SQL Operations.
sample UPDATE sql
sql = "Update [Sheet1$] set name = 'New Name' where id=1"
The following picture shows before and after update of the Sheet.

using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-
informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Update [Sheet1$] set name = 'New Name' where id=1";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to export databse to excel file

The following C# program shows how to export database values to an Excel file . First we load the data from database to a dataset and
then create a new Excel file and write the data to Excel file .
First step is to Load the Product table data to data set , for detail of Product table please refer to Database Structure
Next is to create a new Excel file and write the data from dataset to Excel file.
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn ;
string connectionString = null;
string sql = null;
string data = null;
int i = 0;
int j = 0;

Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";


cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT * FROM Product";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);

for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)


{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.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();
}
}

}
}

How to export DataGridView to excel file

The following C# program demonstrate how to export data fromDatagridview to an Excel file.
The program first connect database and load data from database toDatagridview and then create a new excel file and write the data from
Datagridview to Excel file .

First step is to Load the Product table data to DataGridView , for detail of Product table please refer to Database Structure , and create
new Excel file and write the data from Datagridview to Excel file.

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
SqlConnection cnn ;
string connectionString = null;
string sql = null;

connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";


cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT * FROM Product";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);

dataGridView1.DataSource = ds.Tables[0];
}

private void button2_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;

for (i = 0; i <= dataGridView1.RowCount - 1; i++)


{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
}
}

xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue,


misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.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();
}
}

}
}
How to use C# ArrayList Class

ArrayList is one of the most flexible data structure from CSharpCollections. ArrayList contains a simple list of values. ArrayList
implements the IList interface using an array and very easily we can add , insert , delete , view etc. It is very flexible because we can add
without any size information , that is it will grow dynamically and also shrink .

Add : Add an Item in an ArrayList


Insert : Insert an Item in a specified position in an ArrayList
Remove : Remove an Item from ArrayList
RemoveAt: remove an item from a specified position
Sort : Sort Items in an ArrayList
How to add an Item in an ArrayList ?
Syntax : ArrayList.add(object)
object : The Item to be add the ArrayList
ArrayList arr;
arr.Add("Item1");
How to Insert an Item in an ArrayList ?
Syntax : ArrayList.insert(index,object)
index : The position of the item in an ArrayList
object : The Item to be add the ArrayList
ArrayList arr;
arr.Insert(3, "Item3");
How to remove an item from arrayList ?
Syntax : ArrayList.Remove(object)
object : The Item to be add the ArrayList
arr.Remove("item2")
How to remove an item in a specified position from an ArrayList ?
Syntax : ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)
How to sort ArrayList ?
Syntax : ArrayList.Sort()
The following CSharp source code shows some function in ArrayList

using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
int i = 0;
ArrayList ItemList = new ArrayList();
ItemList.Add("Item4");
ItemList.Add("Item5");
ItemList.Add("Item2");
ItemList.Add("Item1");
ItemList.Add("Item3");
MessageBox.Show ("Shows Added Items");
for (i = 0; i < = ItemList.Count - 1; i++)
{
MessageBox.Show(ItemList[i].ToString());
}
//insert an item
ItemList.Insert(3, "Item6");
//sort itemms in an arraylist
ItemList.Sort();
//remove an item
ItemList.Remove("Item1");
//remove item from a specified index
ItemList.RemoveAt(3);
MessageBox.Show("Shows final Items the ArrayList");
for (i = 0; i < = ItemList.Count - 1; i++)
{
MessageBox.Show(ItemList[i].ToString());
}
}
}
}

When you execute this C# program , at first add five items in the arraylist and displays. Then again one more item inserted in the third
position , and then sort all items. Next it remove the item1 and also remove the item in the third position . Finally it shows the existing
items. 

How to use C# HashTable Class

Hashtable in C# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value
can. We can retrieve items from hashTable to provide the key . Both keys and values are Objects.
The commonly used functions in Hashtable are :

Add : To add a pair of value in HashTable


ContainsKey : Check if a specified key exist or not
ContainsValue : Check the specified Value exist in HashTable
Remove : Remove the specified Key and corresponding Value

Add : To add a pair of value in HashTable


Syntax : HashTable.Add(Key,Value)
Key : The Key value
Value : The value of corresponding key
Hashtable ht;
ht.Add("1", "Sunday");

ContainsKey : Check if a specified key exist or not


Synatx : bool HashTable.ContainsKey(key)
Key : The Key value for search in HahTable
Returns : return true if item exist else false
ht.Contains("1");

ContainsValue : Check the specified Value exist in HashTable


Synatx : bool HashTable.ContainsValue(Value)
Value : Search the specified Value in HashTable
Returns : return true if item exist else false
ht.ContainsValue("Sunday")

Remove : Remove the specified Key and corresponding Value


Syntax : HashTable.Remove(Key)
Key : The key of the element to remove
ht.Remove("1");
The following source code shows some important operations in a HashTable

using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Hashtable weeks = new Hashtable();
weeks.Add("1", "SunDay");
weeks.Add("2", "MonDay");
weeks.Add("3", "TueDay");
weeks.Add("4", "WedDay");
weeks.Add("5", "ThuDay");
weeks.Add("6", "FriDay");
weeks.Add("7", "SatDay");
//Display a single Item

MessageBox.Show(weeks["5"].ToString ());
//Search an Item
if (weeks.ContainsValue("TueDay"))
{
MessageBox.Show("Find");
}
else
{
MessageBox.Show("Not find");
}
//remove an Item
weeks.Remove("3");
//Display all key value pairs
foreach (DictionaryEntry day in weeks )
{
MessageBox.Show (day.Key + " - " + day.Value );
}
}
}
}

When you execute this C# program it will add seven entries in the hashtable. The first message it will display the item 5. Then it check the
value "TueDay" is existing or not . Next it remove the third item from HashTable. Finaly it displays all items exist in the HashTable. 

How to use C# Stack Class

The Stack class represents a last-in-first-out (LIFO) Stack of Objects. Stack follows the push-pop operations. That is we can Push
(insert) Items into Stack and Pop (retrieve) it back . Stack is implemented as a circular buffer. It follows the Last In First Out (LIFO)
system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a
Stack, the capacity is automatically increased as required through reallocation.
Commonly used methods :
Push : Add (Push) an item in the Stack data structure
Pop : Pop return the last Item from the Stack
Contains: Check the object contains in the Stack

Push : Add (Push) an item in the Stack data structure


Syntax : Stack.Push(Object)
Object : The item to be inserted.
Stack days = new Stack();
days.Push("Sunday");
Pop : Pop return the item last Item from the Stack
Syntax : Object Stack.Pop()
Object : Return the last object in the Stack
days.Pop();

Contains : Check the object contains in the Stack


Syntax : Stack.Contains(Object)
Object : The specified Object to be search
days.Contains("Tuesday");
The following CSharp Source code shows some of important functions in Stack Class:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Stack days = new Stack();
days.Push("SunDay");
days.Push("MonDay");
days.Push("TueDay");
days.Push("WedDay");
days.Push("ThuDay");
days.Push("FriDay");
days.Push("SaturDay");
if (days.Count ==7)
{
MessageBox.Show(days.Pop().ToString ());
}
else
{
MessageBox.Show("SaturDay does not exist");
}
}
}
}

When you execute this C# program add seven items in the stack . Then it check the count is equal to 7 , if it is seven then pop() the item.
The message box will display SaturDay. 

How to use C# Queue Class

The Queue works like FIFO system , a first-in, first-out collection of Objects. Objects stored in a Queue are inserted at one end and
removed from the other. The Queue provide additional insertion, extraction, and inspection operations. We can Enqueue (add) items in
Queue and we canDequeue (remove from Queue ) or we can Peek (that is we will get the reference of first item ) item from Queue. Queue
accepts null reference as a valid value and allows duplicate elements.
Some important functions in the Queue Class are follows :
Enqueue : Add an Item in Queue
Dequeue : Remove the oldest item from Queue
Peek : Get the reference of the oldest item

Enqueue : Add an Item in Queue


Syntax : Queue.Enqueue(Object)
Object : The item to add in Queue
days.Enqueue("Sunday");

Dequeue : Remove the oldest item from Queue (we don't get the item later)
Syntax : Object Queue.Dequeue()
Returns : Remove the oldest item and return.
days.Dequeue();

Peek : Get the reference of the oldest item (it is not removed permanently)
Syntax : Object Queue.Peek()
returns : Get the reference of the oldest item in the Queue
days.peek();
The following CSharp Source code shows some of commonly used functions :

using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Queue days = new Queue();
days.Enqueue("Sunday");
days.Enqueue("Monday");
days.Enqueue("Tuesday");
days.Enqueue("Wednsday");
days.Enqueue("Thursday");
days.Enqueue("Friday");
days.Enqueue("Saturday");

MessageBox.Show (days.Dequeue().ToString ());

if (days.Contains("Monday"))
{
MessageBox.Show("The queue contains Monday");
}
else
{
MessageBox.Show("Does not match any entries");
}
}
}
}

When you execute the above C# source code , you will get Sunday in the messagebox and then it check the Monday is exist in the queue
or not. 

How to use C# NameValueCollection Class

NameValueCollection is used to store a collection of associated Stringkeys and String values that can be accessed either with the key or
with the index. It is very similar to C# HashTable, HashTable also stores data in Key , value format .
NameValueCollection can hold multiple string values under a single key. As elements are added to a NameValueCollection, the capacity
is automatically increased as required through reallocation. The one important thing is that you have to
importSystem.Collections.Specialized Class in your program for using NameValueCollection.

Adding new pairs


NameValueCollection.Add(name,value)
NameValueCollection pair = new NameValueCollection();
pair.Add("High", "80");

Get the value of corresponding Key


string[] NameValueCollection.GetValues(index);
NameValueCollection pair = new NameValueCollection();
pair.Add("High", "80");
string[] vals = pair.GetValues(1);

using System;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Specialized;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
NameValueCollection markStatus = new NameValueCollection();
string[] values = null;

markStatus.Add("Very High", "80");


markStatus.Add("High", "60");
markStatus.Add("medium", "50");
markStatus.Add("Pass", "40");

foreach (string key in markStatus.Keys)


{
values = markStatus.GetValues(key);
foreach (string value in values)
{
MessageBox.Show (key + " - " + value);
}
}
}
}
}

C# Array Examples

Arrays are using for store similar data types grouping as a single unit. We can access Array elements by its numeric index. The array
indexes start at zero. The default value of numeric array elements are set to zero, and reference elements are set to null .
Declaring and Initializing an Integer Array
int[] array = new int[4]; 

array[0] = 10;
array[1] = 20;
array[2] = 30;
array[3] = 40;
In the above code we declare an Integer Array of four elements and assign the value to array index . That means we assign values to array
index 0 - 4.
We can retrieve these values from array by using a for loop.

for (int i = 0; i < array.Length; i++)


{
MessageBox.Show (array[i]);
}

Also we can declare and initialize an array in one statement.

int[] array = new int[] {10, 20, 30, 40};


Note that in the above code we did not specify the length of the array so the compiler will do it for us.
How to find the length of an Array ?
Array.Length
We can use array.Length to find the length of an Array.

Declaring and Initializing a String Array

string[] week = new string[7];


week[0] = "Sunday";
week[1] = "Monday";
The above C# code declare a string array of 7 strings and assign some values to it.

string[] week = new string[] {"Sunday","Monday","Tuesday"};


The above code declare and initialize a string array with values.

string str = week[1];


We can access the Arrays elements by providing its numerical index, the above statement we access the second value from the week
Array.
In the following program , we declare an Array "week" capable of seven String values and assigns the seven values as days in a week .
Next step is to retrieve the elements of the Array using a for loop . For finding the end of an Array we used the Length function of Array
Object.

string[] week = new string[7];


week[0] = "Sunday";
week[1] = "Monday";
week[2] = "Tuesday";
week[3] = "Wednsday";
week[4] = "Thursday";
week[5] = "friday";
week[6] = "Saturday";
for (int i = 0; i &lt; = week.Length-1; i++)
{
MessageBox.Show(week[i]);
}

An array can be resized with Array.Resize < T > Method , that means We make an array bigger or smaller. Array.Resize < T > Method
Changes the number of elements of a one-dimensional array to the specified new size.
Array.Resize < T > - T is the type of the elements of the array.
This method should be used with only one dimensional Array. This method allocates a new array with the specified size, copies elements
from the old array to the new one, and then replaces the old array with the new one.
Resize Array

// Initialize array for example


char[] array = new char[5];
array[0] = 'A';
array[1] = 'B';
array[2] = 'C';
array[3] = 'D';
array[4] = 'E';
for (int i = 0; i < array.Length; i++)
{
MessageBox.Show (array[i].ToString ());
}
Array.Resize(ref array, 3);
for (int i = 0; i < array.Length; i++)
{
MessageBox.Show(array[i].ToString ());
}
Array.Resize(ref array, 3);
In the above code we resize the array to 3 elements.

int[] array = { 10, 30, 50 }; //array declaration


foreach (int element in array)
{
Console.WriteLine(element);
}

How to check if a value exists in an array ?


The following program shows how to find an element from an Array

string stringToCheck = "GHI";


string[] stringArray = { "ABC", "DEF", "GHI", "JKL" };
foreach (string x in stringArray)
{
if (x.Equals (stringToCheck))
{
MessageBox.Show("Find the string ..." + x);
}
}

How to for each loop in C# Array

Arrays are using for store similar data types grouping as a single unit. We can access Array elements by its numeric index. The array
indexes start at zero. The default value of numeric array elements are set to zero, and reference elements are set to null. Click the
following link to learn more about C# Arrays.
CSharp Array
Array Declaration and initialization
string[] week = new string[] {"Sunday","Monday","Tuesday"};
Retrieve a single item from Array.
string str = week[1];
It is very convenient to retrieve the Array elements using foreach loop . The following C# program shows how to retrieve the elements in
an Array using foreach loop.

using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string[] week = new string[7];
week[0] = "Sunday";
week[1] = "Monday";
week[2] = "Tuesday";
week[3] = "Wednsday";
week[4] = "Thursday";
week[5] = "friday";
week[6] = "Saturday";

foreach (string day in week)


{
MessageBox.Show(day);
}
}
}
}

How to use C# List Class

C# List Examples
The Collection classes are a group of classes designed specifically for grouping together objects and performing tasks on them. List class
is a collection and defined in the System.Collections.Generic namespace and it provides the methods and properties like other Collection
classes such as add, insert, remove, search etc.
The C# List < T > class represents a strongly typed list of objects that can be accessed by index.
List < T >
The parameter T is the type of elements in the list.
How to add items in List collection ?
Add Integer values in the List collection

List<int> iList = new List<int>();


iList.Add(2);
iList.Add(3);
iList.Add(5);
iList.Add(7);
Add String values in the List

List<string> colors = new List<string>();


colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");
How to count number of items in a List ?
You can use count property to know the number of items in the List collection

colors.Count
How to retrieve items from List ?
You can retrieve items from List collection by using for loops.
foreach loop

foreach (string color in colors)


{
MessageBox.Show(color);
}
for loop

for (int i = 0; i < colors.Count; i++)


{
MessageBox.Show(colors[i]);
}
How to insert an item in the List ?
You can use insert(index,item) method to insert an in the specified index.

colors.Insert(1, "violet");
In the above code the color "violet" inserted in the index position 1.
How to remove an item from List collection ?
Remove() can use to remove item from List collection.

colors.Remove("violet");
How to check if an item exist in the List collection ?
You can use List.Contains() methods to check an item exists in the List

if (colors.Contains("Blue"))
{
MessageBox.Show("Blue color exist in the list");
}
How to copy an Array to a List collection ?

string[] strArr = new string[3];


strArr[0] = "Red";
strArr[1] = "Blue";
strArr[2] = "Green";
//here to copy array to List
List<string> arrlist = new List<string>(strArr);
Finally clear method remove all the items from List collection.

arrlist.Clear ();
The following C# program shows the implementation of the above functionalities in List collection.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
List < string > colors = new List < string > ();

//add items in a List collection


colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");

//insert an item in the list


colors.Insert(1, "violet");

//retrieve items using foreach loop


foreach (string color in colors)
{
MessageBox.Show(color);
}

//remove an item from list


colors.Remove("violet");

//retrieve items using for loop


for (int i = 0; i < colors.Count; i++)
{
MessageBox.Show(colors[i]);
}

if (colors.Contains("Blue"))
{
MessageBox.Show("Blue color exist in the list");
}
else
{
MessageBox.Show("Not exist");
}

//copy array to list


string[] strArr = new string[3];
strArr[0] = "Red";
strArr[1] = "Blue";
strArr[2] = "Green";
List < string > arrlist = new List < string > (strArr);

foreach (string str in strArr)


{
MessageBox.Show(str);
}

//call clear method


arrlist.Clear ();

MessageBox.Show(arrlist.Count.ToString ());
}
}
}

C# Dictionary

How to C# Dictionary
A Dictionary class is a data structure that represents a collection of keys and values pair of data. The key is identical in a key-value pair
and it can have at most one value in the dictionary, but a value can be associated with many different keys.
This class is defined in the System.Collections.Generic namespace, so you should import or using System.Collections.Generic namespace.

using System.Collections.Generic
Syntax:

Parameters :

TKey - The type of the keys in the dictionary.


TValue - The type of the values in the dictionary.
e.g.

Dictionary<string, string>
Dictionary<string, int>
Adding Values to Dictionary
Add method in Dictionary takes two parameters, one for the key and one for the value.
Syntax:

public void Add(TKey key,TValue value)


e.g.
dictionary.Add("dozen",12);
Key in a Dictionary should not be null, but a value can be, if TValue is a reference type.

Dictionary<string, int> dict = new Dictionary<string, int>();


dict.Add("one", 1);
dict.Add("two", 2);
dict.Add("three", 3);
dict.Add("four", 4);
Retrieve Key-Value pair from Dictionary
We can retrieve values from Dictionary using foreach loop

foreach (KeyValuePair<string, int> pair in dict)


{
MessageBox.Show(pair.Key.ToString ()+ " - " + pair.Value.ToString () );
}
Search for a Key
We can search a Key in Dictionary by using the ContainsKey method to test whether a key exists or not. ContainsKey computes the
hashcode for its argument and checks the internal structures in the Dictionary.

if (dict.ContainsKey("four") == true)
{
MessageBox.Show(dict["four"].ToString ());
}
else
{
MessageBox.Show("Key does not exist");
}
Dictionary Vs HashTable
Dictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can't insert any random object
into it, and you don't have to cast the values you take out. Since both Dictionary and Hashtable are internally hashtables, so fast access to
many-item data according to key, also both need immutable and unique keys.
Following is a full source code of adding and retrieving key values pairs in Dictionary

Dictionary < string, int > dict = new Dictionary < string, int > ();
dict.Add("one", 1);
dict.Add("two", 2);
dict.Add("three", 3);
dict.Add("four", 4);

foreach (KeyValuePair < string, int > pair in dict)


{
MessageBox.Show(pair.Key.ToString() + " - " + pair.Value.ToString());
}

C# String Tutorial

A string in CSharp is an object of type String whose value is text. The string type represents a string of Unicode Characters . String
objects areimmutable that is they cannot be changed after they have been created. String is an alias for System.String in the .NET
Framework. Initialize a string with the Empty constant value to create a new String object whose string is of zero length.
From the following links you can see some of commonly using C# string operations in detail.

How to use C# string Clone

Clone() method creates and returns a copy of string object. The CSharp string Clone() method returns a reference to this instance of
string.
Object String.Clone()
Returns:
Object : Return the instance of the String
using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
{
string str = "Clone() Test";
string clonedString = null;
clonedString = (String)str.Clone();
MessageBox.Show (clonedString);
}
}
}
}

When you run this C# program you will get the same content of the first string "Clone() Test" 

How to use C# string Compare

The CSharp String Compare function compares two stringslexicographically . The comparison is based on the Unicode value of each
character in the string.
int string.Compare(string str1,string str2)
It returns an Integer indication lexical relationship between the two comprehends
Parameters:
string str1 : Parameter String
string str2 : Parameter String
Returns:
Integer : returns less than zero, zero or greater than zero.
Less than zero : str1 is less than str2
zero : str1 is equal to str2
Greater than zero : str1 is greater than str2

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str1 = null;
string str2 = null;

str1 = "csharp";
str2 = "CSharp";

int result = 0;
result = string.Compare(str1, str2);
MessageBox.Show(result.ToString());

result = string.Compare(str1, str2, true);


MessageBox.Show(result.ToString());
}
}
}

When you run this C# program first u will get -1 in message box and then 0 

How to use C# string Concat

Concat in CSharp String Class Concatenates the two specified string and create a new string.
string concat(string str1,string str2)
String Concat method returns a new String
Parameters:
String str1 : Parameter String
String str2 : Parameter String
Returns:
String : A new String return with str1 Concat with str2

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str1 = null;
string str2 = null;

str1 = "Concat() ";


str2 = "Test";
MessageBox.Show(string.Concat(str1, str2));
}
}
}

When you run this C# source code you will get "Concat() Test " in message box. 

How to use C# string Contains

The CSharp Contains method returns true if and only if this string contains the specified sequence of char values.
bool string.containe(string str)
Parameters:
String str - input String for search
Returns:
Boolean - Yes/No
If the str Contains in the String then it returns true
If the str does not Contains in the String it returns False
For ex: "This is a Test".Contains("is") return True
"This is a Test".Contains("yes") return False
Exceptions:
System.ArgumentNullException : If the argument is null
using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str = null;
str = "CSharp TOP 10 BOOKS";
if (str.Contains("TOP") == true)
{
MessageBox.Show("The string Contains() 'TOP' ");
}
else
{
MessageBox.Show("The String does not Contains() 'TOP'");
}
}
}
}

When you run the C# program you will get the MessageBox with message "The string Contains() 'TOP' " 

How to use C# string Copy

CSharp String Copy method is create a new String object with the same content
string string.Copy(string str)
Parameters:
String str : The argument String for Copy method
Returns:
String : Returns a new String as the same content of argument String
Exceptions:
System.ArgumentNullException : If the argument is null.

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str1 = null;
string str2 = null;

str1 = "CSharp Copy() test";


str2 = string.Copy(str1);

MessageBox.Show(str2);
}
}
}

When you run this C# source code you will get same content of str1 in str2 

How to use C# string CopyTo

CSharp string CopyTo method Copies a specified number of characters from a specified position in this instance to a specified position in
an array of characters.
void string.CopyTo(int sourceIndex,char[] destination,
int destinationindex,int count)
Parameters:
int sourceIndex : The starting position of the source String
char[] destination : The character Array
int destinationindex : Array element in the destination
int count : The number of characters to destination

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str1 = "CopyTo() sample";
char[] chrs = new char[6];
str1.CopyTo(0, chrs, 0, 6);
MessageBox.Show(chrs[0].ToString() + chrs[1].ToString() + chrs[2].ToString()+ chrs[3].ToString() + chrs[4].ToString() +
chrs[5].ToString());
}
}
}

When you run this C# Source code you will get CopyTo in MessageBox 

How to use C# string EndsWith

EndsWith in C# string Class check if the Parameter String EndsWith the Specified String
bool string.EndsWith(string suffix)
Parameters:
suffix - The passing String for it EndsWith
Returns:
Boolean - Yes/No
If the String EndsWith the Parameter String it returns True
If the String doesn't EndsWith the Parameter String it return False
For ex : "This is a Test".EndsWith("Test") returns True
"This is a Test".EndsWith("is") returns False
Exceptions:
System.ArgumentNullException : If the argument is null

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str = null;
str = "VB.NET TOP 10 BOOKS";
if (str.EndsWith("BOOKS") == true)
{
MessageBox.Show("The String EndsWith 'BOOKS' ");
}
else
{
MessageBox.Show("The String does not EndsWith 'BOOKS'");
}
}
}
}

When you execute the C# program you will get a message box like "The String EndsWith 'BOOKS' " 

How to use C# string Equals

C# String Equals function is to check the specified two String Object values are same or not
bool string.Equals(string str1,string str2)
Parameters:
String str1 : The String argument
String str2 : The String argument
Returns:
Boolean : Yes/No
It return the values of the two String Objects are same
For ex :
Str1 = "Equals()"
Str2 = "Equals()"
String.Equals(Str1,Str2) returns True
String.Equals(Str1.ToLower,Str2) returns False
Because the String Objects values are different

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str1 = "Equals";
string str2 = "Equals";

if (string.Equals(str1, str2))
{
MessageBox.Show("Strings are Equal() ");
}
else
{
MessageBox.Show("Strings are not Equal() ");
}
}
}
}

When you run this C# program you will get message "Strings are Equal() " 

How to use C# string Format

string Format method replace the argument Object into a text equivalent System.String.


string string.format(string format,Object arg0)
Parameters:
String format : The format String
The format String Syntax is like {indexNumber:formatCharacter}
Object arg0 : The object to be formatted.
Returns:
String : The formatted String
Exceptions:
System.ArgumentNullException : The format String is null.
System.FormatException : The format item in format is invalid.
The number indicating an argument to format is less than zero, or greater than or equal to
the number of specified objects to format.
examples :
Currency :
String.Format("{0:c}", 10) will return $10.00
The currency symbol ($) displayed depends on the global locale settings.
Date :
String.Format("Today's date is {0:D}", DateTime.Now)
You will get Today's date like : 01 January 2005
Time :
String.Format("The current time is {0:T}", DateTime.Now)
You will get Current Time Like : 10:10:12

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
double dNum = 0;
dNum = 32.123456789;
MessageBox.Show("Formated String " + string.Format("{0:n4}", dNum));
}
}
}

When you run this C# source code you will get "Formated String 32.1234" 

How to use C# string IndexOf

The IndexOf method in string Class in C# returns the index of the first occurrence of the specified substring.
int string.IndexOf(string str)
Parameters:
str - The parameter string to check its occurrences
Returns:
Integer - If the parameter String occurred as a substring in the specified String
it returns position of the first character of the substring .
If it does not occur as a substring, -1 is returned.
Exceptions:
System.ArgumentNullException: If the Argument is null.
example:
"This is a test".IndexOf("Test") returns 10
"This is a test".IndexOf("vb") returns -1

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str = null;
str = "CSharp TOP 10 BOOKS";
MessageBox.Show(str.IndexOf("BOOKS").ToString());
}
}
}

When you execute this C# program you will get the number 14 in the message box. That means the substring "BOOKS" occurred and start
in the position 14. 

How to use C# string Insert

The Insert() function in String Class will insert a String in a specified index in the String instance.
string string.Insert(int ind,string str)
Parameters:
ind - The index of the specified string to be inserted.
str - The string to be inserted.
Returns:
String - The result string.
Exceptions:
System.ArgumentOutOfRangeException: startIndex is negative or greater than the length of this instance
System.ArgumentNullException : If the argument is null.
example:
"This is Test".Insert(8,"Insert ") returns "This is Insert Test"

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str = "This is CSharp Test";
string insStr = "Insert ";
string strRes = str.Insert(15, insStr);
MessageBox.Show(strRes);
}
}
}

When you execute this C# program you will get the message box showing "This is CSharp Insert Test" 

How to use C# string Length

The Length property in String Class returned the number of characters occurred in a String.


int string.length
Returns:
Integer : The number of characters in the specified String
example:
"This is a Test".Length returns 14.

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str = null;
str = "This is a Test";
MessageBox.Show(str.Length.ToString());
}
}
}

When you execute this C# source code you will get 14 in the messagebox. 

How to use C# string Split

C# Split() handles splitting upon given string and character delimiters. It returns an array of String containing the substrings delimited by
the given System.Char array.
If your String contains "dd-mm-yy", split on the "-" character to get an array of: "dd" "mm" "yy".
The String Split method ignores any element of separator whose value is null or the empty string ("").
Syntax :
string[] string.split(string[] separator)
Parameters:
separator - the given delimiter
Returns:
An array of Strings delimited by one or more characters in separator

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str = null;
string[] strArr = null;
int count = 0;
str = "CSharp split test";
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
for (count = 0; count < = strArr.Length - 1; count++)
{
MessageBox.Show(strArr[count]);
}
}
}
}

When you execute this C# programme , you will get "CSharp" "split" "test" in separate messagebox. 

How to use C# string Substring

Substring in C# string Class returns a new string that is a substring of this string. The substring begins at the specified given index and
extended up to the given length.
string string.substring(int startIndex,int length)
Parameters:
startIndex: The index of the start of the substring.
length: The number of characters in the substring.
Returns:
The specified substring.
Exceptions:
System.ArgumentOutOfRangeException : the beginIndex or length less than zero, or the begin index + length not within the specified
string

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str = null;
string retString = null;
str = "This is substring test";
retString = str.Substring(8, 9);
MessageBox.Show(retString);
}
}
}

When you execute this C# program , it will display "subtring" in the messagebox. 

How to validate a string in C#

TryParse is using for determine whether a string is a valid representation of a specified numeric type or not. TryParse method that is
implemented by all primitive numeric types and also by types such as DateTime and IPAddress.
bool int.TryParse(string param , out int result)
Parameters:
param: The parameter string.
result: The result will store in this variable
Returns:
returns True or False

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
bool isNumeric;
int i;
string str = "100";
isNumeric = int.TryParse(str, out i);
MessageBox.Show("The value of i is " + i);
}
}
}

How to C# String Null

How to handle null String in C#?


A C# string is an array of characters declared using the string keyword. String objects are immutable, meaning that they cannot be
changed once they have been created.
What is C# null ?
The null keyword is a special case for a variable value. The implementation of C# on the CLR represents a null reference by zero bits.
When defining a string in a class, dont initialize it to null. Instead, initialize it to the constant string.Empty
What is Empty Strings ?
An empty string is an instance of a System.String object that contains zero characters. You can call methods on empty strings because
they are valid System.String objects.
string s = "";
What is Null Strings ?
A null string does not refer to an instance of a System.String object and any attempt to call a method on a null string results in a
NullReferenceException. e.g. given below
string str = null;
int len = str.Length;
When run the above code it will throw NullReferenceException.
How to check null String in c#?
You may use the null keyword to check or assign the value of an object.
string str =null ;
if (str == null)
{
MessageBox.Show("String is null");
}
In the above code we created a string Object and assigned null and next we check the string is null or not.
IsNullOrEmpty method
IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is null or its value is Empty.
string str =null;
if (string.IsNullOrEmpty(str))
{
MessageBox.Show("String is empty or null");
}

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string str =null;

if (str == null)
{
MessageBox.Show("String is null");
}
else
{
MessageBox.Show("String is not null");
}

str = "test";
if (string.IsNullOrEmpty(str))
{
MessageBox.Show("String is empty or null");
}
else
{
MessageBox.Show("String is not empty or null");
}

}
}
}

C# File Operations Tutorial

The classes in the namespace System.IO provides various methods to retrieve and changes information about Files as well as Directories .
In C#, to perform a file I/O operation, you can use the same familiar basics of creating, opening, closing, reading, and writing using .NET
Frameworkequivalent classes and methods. The following tutorial provides various operations in Directories as well as Files using
System.IO namespace.

How to use C# Directory Class

Directory class in CSharp exposes methods to create , delete , move etc. operations to directories and subdirectories . Because of the static
nature of C# Directory class , we do not have to instantiate the class. We can call the methods in the C# Directory class directly from the
Directory class itself.
How to create a directory using Directory class in C# ?
In order to create a new directory using Directory class in C# , we can callCreateDirectory method directly from Directory class.
Syntax : Directory.CreateDirectory(string DirPath)
DirPath : The name of the new directory
CSharp Code : Directory.CreateDirectory("c:\\testDir1");
How to check a directory exist or not using Directory class in C# ?
Before we creating a directory or folder , we usually check that directory or folder exist or not. In C# we are using Exists method in the
Directory class.
Syntax : bool Directory.Exist(string DirPath)
DirPath : The name of the directory
bool : Returns true or false -
if directory exist it Returns true , else it Returns false
CSharp Code : Directory.Exists("c:\\testDir1")
How to move a Directory using Directory class in C# ?
If we want to move a directory and its contents from one location to another , we can use the Move method in the C# Directory class.
Syntax : void Directory.Move(string sourceDirName,string destDirName)
sourceDirName : The source directory we want to move.
destDirName : The destinations directory name.
CSharp Code : Directory.Move("c:\\testDir1\\testDir2", "c:\\testDir");
How to delete a Directory using Directory class in C# ?
When we want to delete a directory we can use the Delete method in the C# Directory class
Syntax : void Directory.Delete(string DirPath)
DirPath : The Directory we want to delete.
CSharp Code : Directory.Delete("c:\\testDir1");
The following C# source code shows some operations in Directory class

using System;
using System.Windows.Forms;
using System.IO;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (Directory.Exists("c:\\testDir1"))
{
//shows message if testdir1 exist
MessageBox.Show ("Directory 'testDir' Exist ");
}
else
{
//create the directory testDir1
Directory.CreateDirectory("c:\\testDir1");
MessageBox.Show("testDir1 created ! ");
//create the directory testDir2
Directory.CreateDirectory("c:\\testDir1\\testDir2");
MessageBox.Show("testDir2 created ! ");
//move the directory testDir2 as testDir in c:\
Directory.Move("c:\\testDir1\\testDir2", "c:\\testDir");
MessageBox.Show("testDir2 moved ");
//delete the directory testDir1
Directory.Delete("c:\\testDir1");
MessageBox.Show("testDir1 deleted ");
}
}
}
}

How to use C# File Class

File class is using for the File operations in C#. We can create , delete , copy etc. operations do with C# File class.
How to create a File using C# File class ?
In order to create a new File using C# File class , we can call Create method in the File class.
Syntax : FileSttream File.Create(string FilePath)
FilePath : The name of the new File Object
CSharp Code : File.Create("c:\\testFile.txt");
How to check a File exist or not using C# File class ?
Before we creating a File object , we usually check that File exist or not. For that we are using the Exists method in the C# File class.
Syntax : bool File.Exists(string FilePath)
FilePath : The name of the File
bool : Returns true or false -
if File exist it Returns true else Returns false
CSharp Code : File.Exists("c:\\testFile.txt")
The following C# source code shows these operations :

using System;
using System.Windows.Forms;
using System.IO;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
if (File.Exists("c:\\testFile.txt"))
{
//shows message if testFile exist
MessageBox.Show ("File 'testFile' Exist ");
}
else
{
//create the file testFile.txt
File.Create("c:\\testFile.txt");
MessageBox.Show("File 'testFile' created ");
}
}
}
}

How to use C# FileStream Class

The FileStream Class represents a File in the Computer. Use the FileStream class to read from, write to, open, and close files on a file
system, as well as to manipulate other file related operating system handles including pipes, standard input, and standard output.
FileStream allows to move data to and from the stream as arrays of bytes. We operate File using FileMode in FileStream Class
Some of FileModes as Follows :
FileMode.Append : Open and append to a file if the file does not exist , it create a new file
FileMode.Create : Create a new file , if the file exist it will append to it
FileMode.CreateNew : Create a new File , if the file exist , it throws exception
FileMode.Open : Open an existing file
How to create a file using C# FileStream Class?
The following C# example shows , how to create and write in a file using FileStream.

using System;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
System.IO.FileStream wFile;
byte[] byteData = null;
byteData = Encoding.ASCII.GetBytes("FileStream Test");
wFile = new FileStream("c:\\streamtest.txt", FileMode.Append);
wFile.Write(byteData, 0, byteData.Length);
wFile.Close();
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

When we execute the above C# source code , it create a new File and write the content to the specified path. 

How to use C# Textreader Class


Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. Textreader
represents a reader that can read a sequential series of characters. The StreamReader and StreamWriter classes are derived from
TextReader and TextWriter classes respectively, which read characters from streams and strings.
The following C# source code shows how to read a file using TextReader.

using System;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
string line = null;
System.IO.TextReader readFile = new StreamReader("C:\\csharp.net-informations.txt");
while (true)
{
line = readFile.ReadLine();
if (line != null)
{
MessageBox.Show (line);
}
}
readFile.Close();
readFile = null;
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to use C# Textreader Class

Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. The
StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively. The following program uses
TextReader , Read the entire content of the file into a String.

using System;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string line = null;
System.IO.TextReader readFile = new StreamReader("C:\\net-informations.txt");
line = readFile.ReadToEnd();
MessageBox.Show(line);
readFile.Close();
readFile = null;
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

When you execute this C# program , TextReader read the entire file in one stretch into a string. 

How to use C# Textreader Class

C# Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. The
StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively. The following C# sample
source code showing how create and write in a file using C# TextWriter .

using System;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
System.IO.TextWriter writeFile = new StreamWriter("c:\\textwriter.txt");
writeFile.WriteLine("csharp.net-informations.com");
writeFile.Flush();
writeFile.Close();
writeFile = null;
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

When you execute this C# source code , you will get a file TextWriter.txt and inside its written csharp.net-informations.com . 
How to use C# BinaryWriter Class

C# BinaryWriter Object works at lower level of Streams. C# BinaryWriter Class is using for write primitive types as binary values in a
specific encoding stream. C# BinaryWriter Object works with Stream Objects that provide access to the underlying bytes. For creating a
BinaryWriter Object , you have to first create a FileStream Object and then pass BinaryWriter to the constructor method .
FileStream writeStream ;
writeStream = new FileStream("c:\\testBinary.dat", FileMode.Create);
BinaryWriter writeBinay = new BinaryWriter(writeStream);
The main advantages of Binary information is that it is not easily human readable and stores files as Binary format is the best practice of
space utilization.

using System;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
FileStream writeStream ;
try
{
writeStream = new FileStream("c:\\csharp.net-informations.dat", FileMode.Create);
BinaryWriter writeBinay = new BinaryWriter(writeStream);
writeBinay.Write("CSharp.net-informations.com binary writer test");
writeBinay.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

BinaryReader you can use in the same way to read as binary. 

How to use C# BinaryReader Class

C# BinaryReader Object works at lower level of Streams. C# BinaryReader is using for read primitive types as binary values in a specific
encoding stream. Binaryreader Object works with Stream Objects that provide access to the underlying bytes. For creating a BinaryReader
Object , you have to first create a FileStream Object and then pass BinaryReader to the constructor method .
FileStream readStream ;
readStream = new FileStream("c:\\testBinary.dat", FileMode.Open);
BinaryReader readBinary = new BinaryReader(readStream);
The main advantages of Binary information is that stores files as Binary format is the best practice of space utilization.

using System;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
FileStream readStream ;
string msg = null;
try
{
readStream = new FileStream("c:\\csharp.net-informations.dat", FileMode.Open);
BinaryReader readBinary = new BinaryReader(readStream);
msg = readBinary.ReadString();
MessageBox.Show(msg);
readStream.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

BinaryWriter you can use in the same way to write as binary. 

How to convert XPS file to Bitmap

XPS stands for XML Paper Specification and is basically an electronic representation of digital documents based on XML. An
XpsDocument contains a FixedDocumentSequence that comprises one or more FixedDocument elements. They are also easy to share
because you can view them on any computer where an XPS viewer is installed, even if the computer does not have the same programs that
you used to create the original documents.
The following C# program convert and xps document to a bitmap image. Create a new C# project and add a Button to Form and add the
following references to your project.
Go to Project->Add References and select these files from .Net tab
windowsbase.dll
ReachFramework.dll
PresentationFramework.dll
PresentationCore.dll

using System;
using System.IO;
using System.IO.Packaging;
using System.Windows.Documents;
using System.Windows.Xps.Packaging;
using System.Windows.Media.Imaging;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
string xpsFile = "c:\\Completed-Form.xps";
xpsToBmp(xpsFile);
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show (ex.Message);
}
}

static public void xpsToBmp(string xpsFile)


{
XpsDocument xps = new XpsDocument(xpsFile, System.IO.FileAccess.Read);
FixedDocumentSequence sequence = xps.GetFixedDocumentSequence();

for (int pageCount = 0; pageCount < sequence.DocumentPaginator.PageCount; ++pageCount)


{
DocumentPage page = sequence.DocumentPaginator.GetPage(pageCount);
RenderTargetBitmap toBitmap = new RenderTargetBitmap((int)page.Size.Width,
(int)page.Size.Height,96,96,System.Windows.Media.PixelFormats.Default);

toBitmap.Render(page.Visual);

BitmapEncoder bmpEncoder = new BmpBitmapEncoder();


bmpEncoder.Frames.Add(BitmapFrame.Create(toBitmap));

FileStream fStream = new FileStream("c:\\xpstobmp" + pageCount + ".bmp", FileMode.Create, FileAccess.Write);


bmpEncoder.Save(fStream);
fStream.Close();
}
}
}
}

How to C# Path Class

C# provides effective ways of dealing with filenames and paths from its namespace System.IO . The Path Class performs operations on
String instances that contain file or directory path information. The members of the Path class enable you to quickly and easily perform
common operations such as returns filenae , extensios etc.
The following are the some important operations in C# Path Class:
GetDirectoryName - Returns the directory information for the specified path string.
GetExtension - Returns the extension of the specified path string.
GetFileName - Returns the file name and extension of the specified path string.
GetFileNameWithoutExtension - Returns the file name of the specified path string without the extension.
GetFullPath - Returns the absolute path for the specified path string.
Get Current Application Path
C# Class application in System.Windows.Forms namespace has static property called ExecutablePath . To get the current application path
we can use GetDirectoryName of Path class with ExecutablePath as parameter.
applicationPath = Path.GetDirectoryName(Application.ExecutablePath)
It will return the current directory path of the .exe file .

using System;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string tmpPath = "c:\\windows\\inf\\wvmic.inf";

string fileExtension = Path.GetExtension(tmpPath);


string filename = Path.GetFileName(tmpPath);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(tmpPath);
string rootPath = Path.GetPathRoot(tmpPath);
string directory = Path.GetDirectoryName(tmpPath);
string fullPath = Path.GetFullPath(tmpPath);

MessageBox.Show(directory);

}
}
}

How to create a pdf file in C#

PDF (Portable Document Format) is a file format that has replicate all the characteristics of a printed document that you can read, write,
print or forward to someone else. You can create PDF file programmatically from C# applications very easily. When you create
documents, graphics etc. they look just like they would if printed. PDFsharp is the Open Source library that easily creates PDF documents
from c# language. PDFSharp library allows you to create PDF files directly from your C# application.
You can freely download the Assemblies version from the following link:Download PDFsharp Assemblies
Steps to create PDF file programmatically.
1. Download the Assemblies from the above mentioned url.
2. Extract the .zip file to your desired location (filename :PDFsharp-MigraDocFoundation-Assemblies-1_31.zip)
3. Create a New C# Project
4. Add pdfsharp reference in C# Project
5. In Solution Explorer, right-click the project node and click Add Reference. In this project we are using GDI+ libraries.

6. In the Add Reference dialog box, select the BROWSE tab and select the Assembly file location (step 2)
7. Select all files and click OK
After you add the reference files to your C# project , solution explorer look like the following image.

Now you can start programming to create a New PDF document.


First you should create a PDF document Object

PdfDocument pdf = new PdfDocument();


Next step is to create a an Empty page.

PdfPage pdfPage = pdf.AddPage();


Then create an XGraphics Object

XGraphics graph = XGraphics.FromPdfPage(pdfPage);


Also create the Font object from XFont

XFont font = new XFont("Verdana", 20, XFontStyle.Bold);


Next step is that you should write the content to PDF File.

graph.DrawString("This is my first PDF document", font, XBrushes.Black,


new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
XStringFormats.Center will place the your content to the center of the PDF page.
Now you can save the document as .pdf

pdf.Save("firstpage.pdf");
You can specify the file path in the pdf.save function.
After save the file , you can double click and open the pdf file. Then you can see the following content in your pdf file.
Drag a Button on the Form and copy and paste the following code in the button1_Click event.

using System;
using System.Windows.Forms;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
PdfDocument pdf = new PdfDocument();
pdf.Info.Title = "My First PDF";
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
graph.DrawString("This is my first PDF document", font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point,
pdfPage.Height.Point), XStringFormats.Center);
string pdfFilename = "firstpage.pdf";
pdf.Save(pdfFilename);
Process.Start(pdfFilename);
}
}
}

How to create PDF file from Text file

Pdfsharp is a popular open source framework which could be used to create PDF files programmatically. In many situations we need PDF
documents instead of text documents because text files are listed as the simplest file format, which limits users only to edit words. From
the following steps you can easily convert a text file to a PDF formated document.
You can freely download the Assemblies version from the following link:Download PDFsharp Assemblies
After download the zip file, extract it and add the reference to your c# project
If you want to know the step by step tutorial on how to create your first pdf file programmatically, follow the link : How to create PDF file
programmatically
Steps to create PDF file programmatically.
First you need a Text Reader Object to read the text from Text file.

System.IO.TextReader readFile = new StreamReader("Text.txt");


Next step is to create a PDF Object and a Page Object.

PdfDocument pdf = new PdfDocument();


PdfPage pdfPage = pdf.AddPage();
Also initialize the Graphics and Font

XGraphics graph = XGraphics.FromPdfPage(pdfPage);


XFont font = new XFont("Verdana", 20, XFontStyle.Regular );
Now your PDF Object is ready to write the contents, so the next step is to read the content from the Text file and write to the PDF .

line = readFile.ReadLine();
graph.DrawString(line, font, XBrushes.Black, new XRect(40, yPoint, pdfPage.Width.Point, pdfPage.Height.Point),
XStringFormats.TopLeft);
In the above code we set X as 40 pixels from the left side and Y as a variable "yPoint", because after write the each line, yPoint will
increase 40 pixels line spce then only you get a resonable space between lines.
yPoint = yPoint + 40;
After read all the line from Txt file, you can save the PDF file with your desired name with .pdf extension.

pdf.Save("yourflename.pdf");
Then close the Reader Object.

readFile.Close();
readFile = null;
Your pdf file look like the following image:

The following program shows how to generate a PDF file from Text file content.

using System;
using System.Windows.Forms;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
string line = null;
System.IO.TextReader readFile = new StreamReader("Text.txt");
int yPoint = 0;

PdfDocument pdf = new PdfDocument();


pdf.Info.Title = "TXT to PDF";
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Regular );

while (true)
{
line = readFile.ReadLine();
if (line == null)
{
break; // TODO: might not be correct. Was : Exit While
}
else
{
graph.DrawString(line, font, XBrushes.Black, new XRect(40, yPoint, pdfPage.Width.Point, pdfPage.Height.Point),
XStringFormats.TopLeft);
yPoint = yPoint + 40;
}
}

string pdfFilename = "txttopdf.pdf";


pdf.Save(pdfFilename);
readFile.Close();
readFile = null;
Process.Start(pdfFilename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

Write database data to pdf file

A file with .pdf file extension is called PDF (Portable Document Format) file. Nowadays PDF files are frequently used in important
documents such as tax papers, bank statements, and other forms of documents that require the user to fill in data. There is a usual question
that how to read data from a database using sql statements and write that data to a PDF document.
PDFsharp is the Open Source library for creating and modifying Adobe PDF documents programmatically.
You can freely download the Assemblies version from the following link:Download PDFsharp Assemblies
After download the zip file, extract it and add the reference to your c# project

If you want to know the step by step tutorial on how to create your first pdf file programmatically, follow the link : How to create PDF file
programmatically
Write sql result to pdf file
Here we are using Pdfsharp library to generate the PDF document, before that we have to read the data from Database. So we create
connection string and sql for doing this.

connetionString = "Data Source=YourServerName;Initial Catalog=pubs;User ID=sa;Password=zen412";


sql = "select pub_name,city,country from publishers";
connection = new SqlConnection(connetionString);
Write data from Dataset to pdf file
Retrieve the data and store it n a Dataset.

adapter.Fill(ds);
The next step is to create and initialize the PDFSharp Object to create the pdf document.

PdfDocument pdf = new PdfDocument();


PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Regular );
Finally we retrieve each row from the dataset and write to the pdf file.

graph.DrawString(pubname, font, XBrushes.Black, new XRect(40, yPoint, pdfPage.Width.Point, pdfPage.Height.Point),


XStringFormats.TopLeft);
output sample display
The following C# source code shows how to retrieve the data from database and write to the pdf file.

using System;
using System.Windows.Forms;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Data.SqlClient;
using System.Data;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
int yPoint = 0;
string pubname = null;
string city = null;
string state = null;

connetionString = "Data Source=YourServerName;Initial Catalog=pubs;User ID=sa;Password=zen412";


sql = "select pub_name,city,country from publishers";
connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
connection.Close();

PdfDocument pdf = new PdfDocument();


pdf.Info.Title = "Database to PDF";
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Regular );

yPoint = yPoint + 100;

for (i = 0; i < = ds.Tables[0].Rows.Count - 1; i++)


{
pubname = ds.Tables[0].Rows[i].ItemArray[0].ToString ();
city = ds.Tables[0].Rows[i].ItemArray[1].ToString();
state = ds.Tables[0].Rows[i].ItemArray[2].ToString();

graph.DrawString(pubname, font, XBrushes.Black, new XRect(40, yPoint, pdfPage.Width.Point, pdfPage.Height.Point),


XStringFormats.TopLeft);

graph.DrawString(city, font, XBrushes.Black, new XRect(280, yPoint, pdfPage.Width.Point, pdfPage.Height.Point),


XStringFormats.TopLeft);

graph.DrawString(state, font, XBrushes.Black, new XRect(420, yPoint, pdfPage.Width.Point, pdfPage.Height.Point),


XStringFormats.TopLeft);

yPoint = yPoint + 40;


}

string pdfFilename = "dbtopdf.pdf";


pdf.Save(pdfFilename);
Process.Start(pdfFilename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

CSharp Communication Tutorial

The Microsoft .NET framework provides two namespaces, System.Net andSystem.Net.Sockets for managed implementation of Internet
protocols that applications can use to send or receive data over the Internet . Network programming in windows is possible with sockets ,
peer-to-peer Microsoft Windows applications that act as servers and clients to send and receive data.
The System.Net classes provide functionalities that is similar to Microsoft WinInet API, it allows classes to communicate with other
applications by using the Hypertext Transfer Protocol (HTTP), Transmission Control Protocol (TCP), User Datagram Protocol (UDP),
and Socket Internet protocols. From the following chapters you can learn some of important Classes and its uses in C# Programming
Language.

How to send email from C#

The Microsoft .NET framework provides two namespaces, System.Net andSystem.Net.Sockets for managed implementation of Internet
protocols that applications can use to send or receive data over the Internet . SMTP protocol is using for sending email from C#. SMTP
stands for Simple Mail Transfer Protocol . C# using System.Net.Mail namespace for sending email . We can instantiate SmtpClient class
and assign the Host and Port . The default port using SMTP is 25 , but it may vary different Mail Servers .
The following C# source code shows how to send an email from a Gmail address using SMTP server. The Gmail SMTP server name
issmtp.gmail.com and the port using send mail is 587 and also using NetworkCredential for password based authentication.
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
SmtpServer.Port = 587;
SmtpServer.Credentials =
new System.Net.NetworkCredential("username", "password");

using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

mail.From = new MailAddress("your_email_address@gmail.com");


mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

You have to provide the necessary information like your gmail username and password etc. 

How to send email with attachment from C#

C# simplifies network programming in .Net framework. C# describes various protocols using communication programming like Socket
communications , SMTP mail , UDP , URL etc. The System.Net classes uses to communicate with other applications by using the HTTP,
TCP, UDP, Socket etc. In the previous program we saw how to SMTP email from C#describes how to send an email with text body . Here
we are sending an email with an attachment.
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);
The following C# source code shows how to send an email with an attachment from a Gmail address . The Gmail SMTP server name is
smtp.gmail.com and the port using send mail is 587 . Here using NetworkCredential for password based authentication.
SmtpServer.Credentials =
new System.Net.NetworkCredential("username", "password");

using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your_email_address@gmail.com");
mail.To.Add("to_address");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

You have to provide the necessary information like your gmail username and password etc. 

How to send html email from C#

The System.Net classes provide the functionalities that is similar to Microsoft WinInet API . Here we are using System.Net class for
sending an HTML email from the following C# program . In an HTML email , the body part contain HTML codes like HTML pages. In
the previous C# program SMTP email from C# describes how to send an email with a text body . Here instead of text body part we are
sending email with HTML body part.
mail.IsBodyHtml = true;
string htmlBody = "create html page" ;
mail.Body = htmlBody;
The following C# source code shows how to send an email with HTML body part from a Gmail address . The Gmail SMTP server name
is smtp.gmail.com and the port using for send mail is 587 . Here using NetworkCredential for password based authentication.
SmtpServer.Credentials =
new System.Net.NetworkCredential("username", "password");

using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

mail.From = new MailAddress("your_email_address@gmail.com");


mail.To.Add("to_address");
mail.Subject = "Test Mail - 1";

mail.IsBodyHtml = true;
string htmlBody;

htmlBody = "Write some HTML code here";

mail.Body = htmlBody;

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

You have to provide the necessary information like your gmail username and password etc. 

How to send cdo email from C#

The Microsoft .NET framework provides two namespaces, System.Net andSystem.Net.Sockets for managed implementation of Internet
protocols that applications can use to send or receive data over the Internet .
In the previous C# program SMTP email from C# describes how to send an email with text body . Here we are sending an email without
using SMTP protocol through C# programming . Instead of SMTP here we use CDOSYS , Collaboration Data Objects (CDO) for
Windows 2000 library (Cdosys.dll) . The Cdosys.dll library is also known as CDOSYS .
Create a new C# project and add a reference to Microsoft CDO For Windows 2000 Library . From the following picture you can
understand how to add Microsoft CDO For Windows 2000 Library in your C# project.
using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
CDO.Message oMsg = new CDO.Message();
CDO.IConfiguration iConfg;
iConfg = oMsg.Configuration;
ADODB.Fields oFields;
oFields = iConfg.Fields;
ADODB.Field oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"];
oFields.Update();
oMsg.Subject = "Test CDO";
oMsg.From = "from_address";
oMsg.To = "to_address";
oMsg.TextBody = "CDO Mail test";
oMsg.Send();
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

How to find hostname of a computer

The System.Net classes provide functionalities that is similar to MicrosoftWinInet API , it allows classes to communicate with other
applications by using the Hypertext Transfer Protocol (HTTP), Transmission Control Protocol (TCP), User Datagram Protocol (UDP),
and Socket Internet protocols.
The following C# program show how to find the Host name of a computer.
Dns.GetHostName();

using System;
using System.Net;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
MessageBox.Show (Dns.GetHostName());
}
}
}

How to find IP Adress of a computer

Network programming in windows is possible with sockets . C# simplifies network programming through its namespaces like
System.Net and System.Net.Sockets . The System.Net classes provide functionalities that is similar to Microsoft WinInet API.
The System.net namespace provides the information about IP Address . The following C# program shows how to find the IP Address of
a host.

using System;
using System.Windows.Forms;
using System.Net;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
IPHostEntry hostname = Dns.GetHostByName(textBox1.Text );
IPAddress[] ip = hostname.AddressList;
textBox2.Text = ip[0].ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

If you pass localhost in GetHostByName return the IP Address of local machine . 

How to read URL Content from webserver

The .NET framework provides two namespaces, System.Net andSystem.Net.Sockets for network programming. The System.Net classes
use to communicate with other applications by using the HTTP, TCP, UDP and Sockets.
When we want to read the content of an HTML page from a remote webserver in C# we are
using WebRequest and WebResponse Classes. WebResponse return a StreamReader and we can get the content from StreamReader .
The following C# program shows how to read the content of an HTML page using WebRequest and WebResponse Classes.

using System;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
StreamReader inStream ;
WebRequest webRequest ;
WebResponse webresponse ;
webRequest = WebRequest.Create(textBox1.Text);
webresponse = webRequest.GetResponse();
inStream = new StreamReader(webresponse.GetResponseStream());
textBox2.Text = inStream.ReadToEnd();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

How to C# Socket programming

C# simplifies the network programming through its namespaces likeSystem.Net and System.Net.Sockets . A Socket is an End-Point of
To and From (Bidirectional) communication link between two programs (Server Program and Client Program ) running on the same
network . We need two programs for communicating a socket application in C#. A Server Socket Program ( Server ) and a Client Socket
Program ( Client ) .
C# Server Socket Program: A C# Server Socket Program running on a computer has a socket that bound to a Port Number on the same
computer and listening to the client's incoming requests.
C# Client Socket Program: A C# Client Socket Program have to know the IP Address ( Hostname ) of the computer that the C# Server
Socket Program resides and the Port Number assign for listening for client's request .
Once the connection is established between Server and Client , they can communicate (read or write ) through their own sockets.

There are two types of communication protocol uses for Socket Programming in C# , they are TCP/IP ( Transmission Control
Protocol/Internet protocol ) Communication and UDP/IP ( User Datagram Protocol/Internet protocol ) Communication .
In the following section we are going to communicate a C# Server Socket Program and C# Client Socket Program using TCP/IP
Communication Protocol.

The above picture shows a Server and Client communication interfaces in C#.
C# Server Socket Program:
The Server Socket Program is done through a C# Console based application . Here the Server is listening for the Client's request , and
when the C# Server gets a request from Client socket , the Server sends a response to the Client . Click the following link to see in detail
of a C# Server Socket Program.
C# Client Socket Program:
The C# Client Socket Program is a windows based application . When the C# Client program execute , it will establish a connection to the
C# Server program and send request to the Server , at the same time it also receive the response from C# Server . Click the following link
to see in detail ofC# Client Socket Program.
How to run this program ?
The C# Socket Program has two sections.
1. C# Server Socket Program
2. C# Client Socket Program
When you finish coding and build the Server and Client program , First you have to start C# Server Socket Program from DOS prompt ,
then you will get a message "Server Started" in your DOS screen, where the server program is running .
Next step is to start C# Client Socket Program in the same computer or other computers on the same network . When you start the client
program , it will establish a connection to the Server and get a message in client screen " Client Started " , at the same time you can see a
message in the Server screen "Accept connection from client" .
Now your C# Server Socket Program and C# Client Socket Program is get connected and communicated . If you want to communicate the
Server and Client again , click the button in the client program , then you can see new messages in the Server and Client programs
displayed.

C# Server Socket program

The C# Socket Programming has two sections.


1. C# Server Socket Program
2. C# Client Socket Program

Server Socket Program


The Server Socket Program here is a C# Console based Application . This program act as a Server and listening to clients request . Here
we assign a Port No. 8888 for the Server Socket , it is an instance of the C# Class TcpListener , and call its start() method.
TcpListener serverSocket = new TcpListener(8888);
serverSocket.Start();
The next step is to create an infinite loop for monitoring the request from Client's side . When the Server Socket accept a request from the
Client side, it reads the data from NetworkStream and also it write the response to NetworkStream .
From the following C# program you can understand how to create a Socket Server in C# . Create a new C# Console Application Project
and put the following source code into the project.

using System;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;

while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
string serverResponse = "Server response " + Convert.ToString(requestCount);
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}

How to run this program ? 


The C# Socket Programming has two sections. 

1. C# Server Socket Program 

2. C# Client Socket Program 

When you finish coding and build the Server and Client program , First you have to start C# Server Socket Program from DOS prompt ,
then you will get a message " Server Started " in your DOS screen, where the server program is running . 

Next step is to start C# Client Socket Program in the same computer or other computers on the same network . When you start the client
program , it will establish a connection to the Server and get a message in client screen " Client Started " , at the same time you can see a
message in the Server screen " Accept connection from client " . 

Now your C# Server Socket Program and C# Client Socket Program is get connected and communicated . If you want to communicate the
Server and Client again , click the button in the client program , then you can see new messages in the Server and Client programs
displayed.

C# Client Socket program

The C# Socket Programming has two sections.


1. C# Server Socket Program
2. C# Client Socket Program
Client Socket Program
The C# Client Socket Program is the second part of the C# Server Socket Program . The C# Client Socket Program is a Windows based
application . The Client is connected to the Port 8888 of the C# Server Socket Program, and the IP Address (Computer Name) here we
give as 127.0.0.1 , because the Server and Client running on the same machine .
clientSocket.Connect("127.0.0.1", 8888);
When the C# Client program starts , it will connect to the C# Server Socket Program and start to reads data from NetworkStream , and
also write to the NetworkStream . When you start the client program you will get a message from Server "client started". When press the
button at the bottom of Client window, it will send a message to the Server and also receive response from the Server.

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
msg("Client Started");
clientSocket.Connect("127.0.0.1", 8888);
label1.Text = "Client Socket Program - Server Connected ...";
}

private void button1_Click(object sender, EventArgs e)


{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message from Client$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();

byte[] inStream = new byte[10025];


serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
msg("Data from Server : " + returndata);
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
}
}

How to run this program ? 


The C# Socket Programming has two sections. 

1. C# Server Socket Program 

2. C# Client Socket Program 

When you finish coding and build the Server and Client program , First you have to start C# Server Socket Program from DOS prompt ,
then you will get a message " Server Started " in your DOS screen, where the server program is running . 

Next step is to start C# Client Socket Program in the same computer or other computers on the same network . When you start the client
program , it will establish a connection to the Server and get a message in client screen " Client Started " , at the same time you can see a
message in the Server screen " Accept connection from client " . 

Now your C# Server Socket Program and C# Client Socket Program is get connected and communicated . If you want to communicate the
Server and Client again , click the button in the client program , then you can see new messages in the Server and Client programs
displayed.

C# Multi threaded socket programming

C# Multithreaded Socket Programming describes that a Multithreaded Socket Server can communicate with more than one client at the
same time in the same network. The Microsoft .NET framework provides two namespaces, System.Net and System.Net.Sockets for
managed implementation of Internet protocols that applications can use to send or receive data over the Internet .
In the previous chapter C# Socket Programming describes a Server Socket Program can communicate with only one client at a time . That
means, theC# Server Socket Program does not accept more than one C# Client Socket Program connection . From the following picture
you can understand how to a C# Multithreaded Server can communicate with more than one C# Client at the same time .You can see the
basics of Socket Programming in the previous section , before you start this section take a look at C# Socket Programming .
The basic idea behind Multithreaded Socket Programming is, whenever the Server gets a connection request from Client side, the
Server create a separate Client Thread in Server side for communicate with that particular Client Socket. That means, for each Client
Socket there is a separate Client Thread in Server side for independent communication. So the Client can communicate independently
with their own Client Thread in the Server side.
In the following sections you can see in details of How to a C# Multithreaded Socket Programming can communicate with more than one
client at the same time.
The C# Multithreaded Socket Programming has two sections.
1. C# Multi Threaded Server Socket Program
2. C# Multi Threaded Client Socket Program
How to run this program ?
Create C# Multi Threaded Server Socket Program and C# Multi Threaded Client Socket Program in two separate C# projects .
After compile and build the projects, open a DOS prompt and run the Server Program first. Then you will get the message "Server
started" in Server side.
Next you start the Client program , then you can see the message from Server . You can start more than one client at the same time and
communicate with the Server program. If you plan to run more than one client, it is better to run the client program's .exe file to copy in
separate folders and run from .exe file.

C# Multi threaded Server Socket programming

MultiThreaded Server Socket Program here is a C# Console based application , that can handle multiple clients at the same time.
Network programming in windows is possible with sockets , peer-to-peer Microsoft Windows applications that act as servers and clients
to send and receive data. You can see the basics of C# Socket Programming in the previous section , before you start this section take a
look at C# Socket Programming .

The C# Multi Threaded Socket Program has two sections.


1. C# Multithreaded Server Socket Program
2. C# Multi Threaded Client Socket Program
Multithreaded Server Socket Program
Here we create a C# Server Socket from TcpListener Class and listen to PORT 8888 . When the C# Server Socket gets a request from
Client side , the Server passes the instance of the client request to a separate class handleClient .For each call from Server Socket , the
handleClient class create new instances for independent communication with the client. In handleClient class there is a Thread for
handling the communication between the instance of C# Server side client and C# Client from outside .
For each Client request , there is a new thread instant is created in C# Server for separate communication with Client, so we can connect
more than one client at the same time to the C# Server and communicate independently to Server .
Create a new C# Console Application project and put the following source code in the C# project.

using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;

serverSocket.Start();
Console.WriteLine(" >> " + "Server Started");

counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}

clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}

//Class to handle each client request separatly


public class handleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;

while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> " + "From client-" + clNo + dataFromClient);

rCount = Convert.ToString(requestCount);
serverResponse = "Server to clinet(" + clNo + ") " + rCount;
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
}
}
}
}
}

The C# Multi Threaded Socket Program has two sections. 


1. C# Multithreaded Server Socket Program 

2. C# Multi Threaded Client Socket Program 

How to run this program ? 

Create C# Multithreaded Server Socket Program and C# Multi Threaded Client Socket Program in two separate C# projects . 

After compile and build the projects, open a DOS prompt and run the Server Program first.Then you will get the message "Server
started" in Server side. 

Next you start the Client program , then you can see the message from Server . You can start more than one client at the same time and
communicate with the Server program. If you plan to run more than one client, it is better to run the client program's .exe file to copy in
separate folders and run from .exe file.

C# Multi threaded Client Socket programming

C# Multithreaded Client Socket Program here is a C# Windows based application and it can connect to the Server and send the
message to the Server. The C# Server is multithreaded so we can connect more than one Client program to the Server .
The System.Net classes provide functionality that is similar to MicrosoftWinInet API , it allows classes to communicate with other
applications by using the Hypertext Transfer Protocol (HTTP), Transmission Control Protocol (TCP), User Datagram Protocol (UDP),
and Socket Internet protocols. You can see the basics of C# Socket Programming in the previous section , before you start this section take
a look at C# Socket Programming section.
The C# Multi Threaded Socket Program has two sections.
1. C# Multi Threaded Server Socket Program
2. C# Multithreaded Client Socket Program
Multithreaded Client Socket Program
C# MultiThreaded Client Socket Program is a windows based application . Here the client program is connected to Server's PORT 8888 ,
and IP Address here we give Server Address as " 127.0.0.1 " , because Server and Client program run on the same machine.
clientSocket.Connect("127.0.0.1", 8888);
When the Client gets connected to the C# Server , the Server makes a separate thread for Client's communication . So we can connect
more than one client and communicate at the same time.
Create a new C# Windows based application and put the following source code in the Project.

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
msg("Client Started");
clientSocket.Connect("127.0.0.1", 8888);
label1.Text = "Client Socket Program - Server Connected ...";
}

private void button1_Click(object sender, EventArgs e)


{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message from Client$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();

byte[] inStream = new byte[10025];


serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
msg("Data from Server : " + returndata);
}

public void msg(string mesg)


{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
}
}

How to run this program ? 


The C# Multi Threaded Socket Program has two sections. 

1. C# Multi Threaded Server Socket Program 

2. C# Multithreaded Client Socket Program 

Create C# Multi Threaded Server Socket Program and C# Multithreaded Client Socket Program in two separate C# projects . 

After compile and build the projects, open a DOS prompt and run the Server Program first.Then you will get the message "Server
started" in Server side. 

Next you start the Client program , then you can see the message from Server . You can start more than one client at the same time and
communicate with the Server program. If you plan to run more than one client, it is better to run the client program's .exe file to copy in
separate folders and run from .exe file.

How to C# Chat server programming

Network programming in windows is possible with Sockets .The Microsoft .NET framework provides two
namespaces, System.Net andSystem.Net.Sockets for managed implementation of Internet protocols that applications can use to send or
receive data over the Internet .
In the previous section C# Multi Threaded Socket Program we can see aC# Multi Threaded Server Socket Program communicate with
more than one Client at the same time . But there the communication is occurred between Server to Client or Client to Server , there is no
communication between Client to Client . C# Chat Server describes how to a Client can communicate with any number of Clients ,
currently connected to the Chat Server .
The main idea behind the C# Chat Server is that each Client send messages to the Server and the Server broadcast the message to all
Clients currently connected to the Chat Server . From the following picture you can see how a C# TCP Chat Server is handling
communication between Client to Client .

The C# Chat Server program has two sections.


1. C# Chat Server
2. C# Chat Client
How to run Chat Server program ?
Create the C# Chat Server and C# Chat Client are two separate C# projects and compile and build the program. Open a DOS prompt and
run the Server Program first and then run the Client program .
In the Client program, Enter a Chat name and click " Connect to Server " button . Then you can see the message in the Server program
User "Joined Chat Room " . Similarly you can connect more than one Clients at the same time and start chatting each other. If you plan
to run more than one client, it is better to copy the .exe file in separate folders and run from the .exe file.

How to C# Chat Server

The basic function of the Chat Server here is to listen to the incoming request from Clients, and when the Server got a message ,
it Broadcastthe message to all the Clients currently connected to the Chat Server .
In the previous section C# Multi Threaded Socket Program we saw a Multithreaded Server Socket Program communicate with more than
one Clients at the same time .
The C# Chat Server Program has two sections.
1. Chat Server
2. C# Chat Client
Chat Server
The Chat Server here is a C# Console Based Application and is listen to the PORT 8888 for the connection request from clients . When
the server got a connection request, it add the name of the Client into a clientsList ( Here it is a Hashtable ) and create a new thread for
communicate with the Server .
clientsList.Add(dataFromClient, clientSocket);
When the Server gets a message from any client , it select all the Clients from the clientsList and send the message ( Broadcast ) to all
Clients ( ie we can say Broadcast ) in the clientsList . So all Client can see the message of each others and they can communicate through
Server.
broadcast(dataFromClient, clNo, true);
The client list we implemented as a HashTable . The clientsList stores the Client Name ( ie here the first message from Client ) and create
an instance of the Client Socket .
When a Client connected to Server , the Server create a new Thread for communication . Here we implement a Class handleClient for
handling Client as a separate Thread . The Class handleClient has a functiondoChat() is handling the communication between the Server
side Client.
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
When Server gets a message from any of the connected Chat Client , the Server Broadcast the message to all Clients. Here we implement
a function broadcast for sending messages to all Clients .
Create a new C# Console Based Application and put the following source code into the Project.

using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
public static Hashtable clientsList = new Hashtable();

static void Main(string[] args)


{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;

serverSocket.Start();
Console.WriteLine ("Chat Server Started ....");
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();

byte[] bytesFrom = new byte[10025];


string dataFromClient = null;

NetworkStream networkStream = clientSocket.GetStream();


networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

clientsList.Add(dataFromClient, clientSocket);

broadcast(dataFromClient + " Joined ", dataFromClient, false);

Console.WriteLine(dataFromClient + " Joined chat room ");


handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
}

clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}

public static void broadcast(string msg, string uName, bool flag)


{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;

if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}

broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
} //end broadcast function
}//end Main class

public class handleClinet


{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;

public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)


{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}

private void doChat()


{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;

while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
rCount = Convert.ToString(requestCount);

Program.broadcast (dataFromClient, clNo, true);


}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
} //end class handleClinet
}//end namespace

The C# Chat Server Program has two sections. 


1. Chat Server 

2. C# Chat Client 

How to run Chat Server program ? 

Create the C# Chat Server and C# Chat Client are two separate C# projects and compile and build the program. Open a DOS prompt and
run the Server Program first and then run the Client program . 

In the Client program, Enter a Chat name and click " Connect to Server " button . Then you can see the message in the Server program
User "Joined Chat Room" . Similarly you can connect more than one Clients at the same time and start chatting each other. If you plan to
run more than one client, it is better to copy the .exe file in separate folders and run from the .exe file.

How to C# Chat Client

The Microsoft .NET framework provides two namespaces, System.Net andSystem.Net.Sockets for managed implementation of Internet
protocols that applications can use to send or receive data over the Internet . The C# Chat Client here is a Windows based Application and
its main function is to send message to the Chat Server.
In the previous section C# Multi Threaded Socket Program we saw a C# Multithreaded Server Socket Program communicate with more
than one Client at the same time . If you don't know the basics of Socket programming , take a look at the section C# Socket
Programming before you start this section.
The C# Chat Server Program has two sections.
1. C# Chat Server
2. Chat Client
Chat Client
The Chat Client here is to connect the PORT 8888 of the C# Chat Server in " 127.0.0.1 " . Here we give " 127.0.0.1 " , because Chat
Server and Chat Client are running on the same machine . When we start the Chat Client program , we have to enter a User Name for
identifying the client in Server side . The Client program connect to the Chat Server and start a Thread for receive the messages from
Server side client . Here we implement an infinite loop in the function getMessage() and call this function in a Thread .
Create a new C# Windows based project and put the source code in it.

using System;
using System.Windows.Forms;
using System.Text;
using System.Net.Sockets ;
using System.Threading;

namespace WindowsApplication2
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}

private void button2_Click(object sender, EventArgs e)


{
readData = "Conected to Chat Server ...";
msg();
clientSocket.Connect("127.0.0.1", 8888);
serverStream = clientSocket.GetStream();

byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + "$");


serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();

Thread ctThread = new Thread(getMessage);


ctThread.Start();
}

private void getMessage()


{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
}

private void msg()


{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + readData;
}

}
}

The C# Chat Server Program has two sections. 


1. C# Chat Server 

2. Chat Client 

How to run Chat Server program ? 

Create the C# Chat Server and C# Chat Client are two separate C# projects and compile and build the program. Open a DOS Prompt and
run the Server Program first and then run the Client program . 

In the Client program, Enter a Chat name and click " Connect to Server " button . Then you can see the message in the Server program
User "Joined Chat Room" . Similarly you can connect more than one Clients at the same time and start chatting each other. If you plan to
run more than one client, it is better to copy the .exe file in separate folders and run from the .exe file.

How to web browser in C#

The Web Browser control in C# allows you to host Web pages and other web browser enabled documents in your Windows Forms
applications. You can add browser control in your C# projects and it displays the web pages like normal commercial web browsers .You
can use the Browser control to provide integrated HTML based user assistance or Web browsing capabilities in your application.
The The Web Browser control has several properties, methods, and events related to navigation. The following C# program displays a
web page in browser window and also you can retrieve the source code of the same web page with another button click.

using System;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click_1(object sender, EventArgs e)


{
webBrowser1.Navigate(textBox1.Text );
}

private void button2_Click(object sender, EventArgs e)


{
String source = ("viewsource.txt");
StreamWriter writer = File.CreateText(source);
writer.Write(webBrowser1.DocumentText);
writer.Close();
Process.Start("notepad.exe", source);
}
}
}

C# ADO.NET data Providers Tutorial


The .Net Framework includes mainly three Data Providers for ADO.NET . The Microsoft SQL Server , OLEDB and ODBC are the
main Data Providers included in the .Net Framework. You can see from the following links how these Data Providers manage connection
to the Data Sources from your C# applications .
C# SQL Server Connection
C# OLEDB Connection
C# ODBC Connection

The four Objects from the .Net Framework provide the functionality of Data Providers in ADO.NET. They
are Connection Object, CommandObject , DataReader Object and DataAdapter Object. The Connection Object provides physical
connection to the Data Source. The Command Object uses to perform SQL statement or stored procedure to be executed at the Data
Source. The DataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not
update the data. Finally the DataAdapter Object , which populate aDataset Object with results from a Data Source . The following link
shows how to use these Objects in C# applications.
C# Connection
C# Command
C# DataReader
C# DataAdapter

C# ADO.NET Connection

The Connection Object is a part of ADO.NET Data Provider and it is a unique session with the Data Source. The Connection Object is
Handling the part of physical communication between the C# application and the Data Source.
The Connection Object connect to the specified Data Source and open a connection between the C# application and the Data Source,
depends on the parameter specified in the Connection String . When the connection is established , SQL Commands will execute with
the help of the Connection Object and retrieve or manipulate data in the Data Source.
Once the Database activity is over , Connection should be closed and release the Data Source resources .

In C# the type of the Connection is depend on which Data Source system you are working with. The following are the commonly used
Connections from the C# applications.
C# SQL Server Connection
C# OLEDB Connection
C# ODBC Connection

C# SQl Server Connection

The SqlConnection Object is Handling the part of physical communication between the C# application and the SQL Server Database .
An instance of the SqlConnection class in C# is supported the Data Provider for SQL Server Database. The SqlConnection instance takes
Connection String as argument and pass the value to the Constructor statement.
connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
When the connection is established , SQL Commands will execute with the help of the Connection Object and retrieve or manipulate the
data in the database. Once the Database activities is over , Connection should be closed and release the Data Source resources .
cnn.Close();
The Close() method in SqlConnection Class is used to close the Database Connection. The Close method rolls back any pending
transactions and releases the Connection from the SQL Server Database.

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User
ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# OLEDB Connection

The C# OleDbConnection instance takes Connection String as argument and pass the value to the Constructor statement. An instance of
the C# OleDbConnection class is supported the OLEDB Data Provider .
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=yourdatabasename.mdb;";
cnn = new OleDbConnection(connetionString);
When the connection is established between C# application and the specified Data Source, SQL Commands will execute with the help of
theConnection Object and retrieve or manipulate data in the database. Once the Database activities is over Connection should be closed
and release from the data source resources .
cnn.Close();
The Close() method in the OleDbConnection class is used to close the Database Connection. The Close method Rolls Back any pending
transactions and releases the Connection from the Database connected by the OLEDB Data Provider.

using System;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection cnn ;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdatabasename.mdb;";
cnn = new OleDbConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ODBC Connection

An instance of the OdbcConnection Class in C# is supported the ODBC Data Provider. The OdbcConnection instance takes Connection
String as argument and pass the value to the Constructor statement. When the connection is established between C# application and the
Data Source the SQL Commands will execute with the help of the Connection Object and retrieve or manipulate data in the database.
connetionString = "Driver={Microsoft Access Driver (*.mdb)};
DBQ=yourdatabasename.mdb;";
cnn = new OdbcConnection(connetionString);
Once the Database activities is over you should be closed the Connection and release the Data Source resources . The Close() method
inOdbcConnection Class is used to close the Database Connection.
cnn.Close();
The Close method rolls back any pending transactions and releases the Connection from the Database connected by the ODBC Data
Provider .

using System;
using System.Windows.Forms;
using System.Data.Odbc;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OdbcConnection cnn ;
connetionString = "Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;";
cnn = new OdbcConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET Command

The Command Object in ADO.NET executes SQL statements and Stored Procedures against the data source specified in the C#
Connection Object. The Command Object requires an instance of a C# Connection Object for executing the SQL statements .
In order to retrieve a resultset or execute an SQL statement against a Data Source , first you have to create a Connection Object and open
a connection to the Data Source specified in the connection string. Next step is to assign the open connection to the connection property of
theCommand Object . Then the Command Object can execute the SQL statements. After the execution of the SQl statement, the
Command Object will return a result set . We can retrieve the result set using aData Reader .

The Command Object has a property called CommandText , which contains a String value that represents the command that will be
executed against the Data Source. When the CommandType property is set to StoredProcedure, the CommandText property should be set
to the name of the stored procedure.
Click the following links to see some important built in methods uses in the Command Object to execute the SQL statements.
C# ExecuteNonQuery
C# ExecuteReader
C# ExecuteScalar

C# ADO.NET SqlCommand - ExecuteNonQuery

The ExecuteNonQuery() is one of the most frequently used method in SqlCommand Object, and is used for executing statements that do
not return result sets (ie. statements like insert data , update data etc.) .
Command.ExecuteNonQuery();
The ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating
Stored Procedures ,Views etc. perform by the ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update , Delete etc. also
perform by the ExecuteNonQuery() of SqlCommand Object.
The following C# example shows how to use the method ExecuteNonQuery() through SqlCommand Object.

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";


sql = "Your SQL Statemnt Here";

cnn = new SqlConnection(connetionString);


try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

How to C# ADO.NET OleDbCommand - ExecuteNonQuery

The ExecuteNonQuery() is one of the most frequently used method in OleDbCommand Object and is used for executing statements that
do not returns result sets. The ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also.
cmd.ExecuteNonQuery();
The Data Definition tasks like creating Stored Procedures, Views etc. perform by the ExecuteNonQuery() . Also Data Manipulation tasks
like Insert , Update , Delete etc. perform by the ExecuteNonQuery().
The following C# example shows how to use the method ExecuteNonQuery() through OleDbCommand Object.

using System;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection cnn ;
OleDbCommand cmd ;
string sql = null;

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


sql = "Your SQL Statement Here"

cnn = new OleDbConnection(connetionString);


try
{
cnn.Open();
MessageBox.Show("Connection Opened ");
cmd = new OleDbCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in OleDbConnection executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! " + ex.ToString());
}
}
}
}

C# ADO.NET SqlCommand - ExecuteScalar

The ExecuteScalar() in C# SqlCommand Object is using for retrieve a single value from Database after the execution of the SQL
Statement. The ExecuteScalar() executes SQL statements as well as Stored Procedure and returned a scalar value on first column of first
row in the returned Result Set.
If the Result Set contains more than one columns or rows , it will take only the value of first column of the first row, and all other values
will ignore. If the Result Set is empty it will return a NULL reference.
It is very useful to use with aggregate functions like Count(*) or Sum()etc. When compare to ExecuteReader() , ExecuteScalar() uses
fewer System resources.

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";


sql = "Your SQL Statement Here like Select Count(*) from product";

cnn = new SqlConnection(connetionString);


try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
cnn.Close();
MessageBox.Show (" No. of Rows " + count);
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET OleDbCommand - ExecuteScalar

The ExecuteScalar() in C# OleDbCommand Object uses to retrieve a single value from the Database after the execution of SQL
Statements or Stored Procedures.
The ExecuteScalar() executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the returned
Result Set. If the Result Set contains more than one columns or rows , it will return only the first column of the first row value and ignore
all other values . If the Result Set is empty it will return a NULL reference.
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
It is very useful to use with aggregate functions like Count(*) or Sum()etc and also when compare to ExecuteReader() , ExecuteScalar()
uses fewer System resources.

using System;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection cnn ;
OleDbCommand cmd ;
string sql = null;

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";


sql = "Your SQL Statement Here like Select Count(*) from product";

cnn = new OleDbConnection(connetionString);


try
{
cnn.Open();
cmd = new OleDbCommand(sql, cnn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
cnn.Close();
MessageBox.Show (" No of Rows " + count);
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET SqlCommand - ExecuteReader

The ExecuteReader() in C# SqlCommand Object sends the SQL statements to the Connection Object and populate a SqlDataReader
Object based on the SQL statement. When the ExecuteReader method in SqlCommand Object execute , it will instantiate
aSqlClient.SqlDataReader Object.
The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not
update the data it contains. The SqlDataReader cannot be created directly from code, they can created only by calling the ExecuteReader
method of a C# Command Object.

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
SqlDataReader reader ;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";


sql = "Your SQL Statement Here , like Select * from product";

cnn = new SqlConnection(connetionString);


try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader.GetValue(0) + " - " + reader.GetValue(1) + " - " + reader.GetValue(2));
}
reader.Close();
cmd.Dispose();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET OleDbCommand - ExecuteReader

The ExecuteReader() in OleDbCommand Object sends the SQL statements to the C# Connection Object and populate an
OleDbDataReader Object based on the SQL statement. When the ExecuteReader method in OleDbCommand Object execute , it will
instantiate an Object of OleDb.OleDbDataReader .
OleDbDataReader reader = cmd.ExecuteReader();
The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not
update the data. The OleDbDataReader cannot be created directly from the code, they can create only by calling
the ExecuteReader method of a C# Command Object.

using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection cnn ;
OleDbCommand cmd ;
string sql = null;
OleDbDataReader reader ;

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";


sql = "Your SQL Statement Here like Select * from product";

cnn = new OleDbConnection(connetionString);


try
{
cnn.Open();
cmd = new OleDbCommand(sql, cnn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader.GetValue(0) + " - " + reader.GetValue(1) + " - " + reader.GetValue(2));
}
reader.Close();
cmd.Dispose();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET DataReader

DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query results from the Data Sources , which do
not update the data. The DataReader cannot be created directly from code, they can created only by calling the ExecuteReader method of
a Command Object.

SqlDataReader sqlReader = sqlCmd.ExecuteReader();


The DataReader Object provides a connection oriented data access to the Data Sources. A Connection Object can contain only one
DataReader at a time and the connection in the DataReader remains open, also it cannot be used for any other purpose while data is being
accessed. When we started to read from a DataReader it should always be open and positioned prior to the first record.
The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any
row exist .
DataReader.Raed();
Usually we are using two types of DataReader in ADO.NET. They areSqlDataReader and the OleDbDataReader . The
System.Data.SqlClient and System.Data.OleDb are containing these DataReaders respectively. From the following link you can see in
details about these classes in C#.
C# SqlDataReader
C# OleDbDataReader

C# ADO.NET SqlDataReader

SqlDataReader Object provides a connection oriented data access to the SQL Server data Sources from C#
applications. ExecuteReader() in the SqlCommand Object sends the SQL statements to the SqlConnection Object and populate a
SqlDataReader Object based on the SQL statement or Stored Procedures.
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
When the ExecuteReader method in the SqlCommand Object execute , it will instantiate a SqlClient.SqlDataReader Object. When we
started to read from a DataReader it should always be open and positioned prior to the first record. The Read() method in the DataReader
is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist .
SqlDataReader.Read()

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
string sql = null;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";


sql = "Your SQL Statement Here , like Select * from product";

sqlCnn = new SqlConnection(connetionString);


try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
MessageBox.Show(sqlReader.GetValue(0) + " - " + sqlReader.GetValue(1) + " - " + sqlReader.GetValue(2));
}
sqlReader.Close();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET OleDbDataReader

OleDbDataReader Object provides a connection oriented data access to the OLEDB Data Sources through C#
applications. ExecuteReader() in the OleDbCommand Object sends the commands to OleDbConnection Object and populate an
OleDbDataReader Object based on the SQL statements as well as Stored Procedures passed through the OleDbCommand Object.
OleDbDataReader oledbReader = oledbCmd.ExecuteReader();
When the ExecuteReader method in OleDbCommand Object execute , it will instantiate an OleDb.OleDbDataReader Object. When we
started to read from an OleDbDataReader it should always be open and positioned prior to the first record. The Read() method in the
OleDbDataReader is used to read the rows from the OleDbDataReader and it always moves forward to a new valid row, if any row exist .
OleDbDataReader.Read()

using System;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbCommand oledbCmd ;
string sql = null;

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";


sql = "Your SQL Statement Here like Select * from product";

oledbCnn = new OleDbConnection(connetionString);


try
{
oledbCnn.Open();
oledbCmd = new OleDbCommand(sql, oledbCnn);
OleDbDataReader oledbReader = oledbCmd.ExecuteReader();
while (oledbReader.Read ())
{
MessageBox.Show(oledbReader.GetValue(0) + " - " + oledbReader.GetValue(1) + " - " + oledbReader.GetValue(2));
}
oledbReader.Close();
oledbCmd.Dispose();
oledbCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
C# Multiple Result Sets

The DataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update
the data in the Data Source. When the ExecuteReader method in SqlCommand Object execute , it will instantiate a
SqlClient.SqlDataReader Object in C#.
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
In some situations we need to execute multiple SQL statements with the Command Object. In these types of situations the SqlDataReader
returns multiple ResultSets also. In order to retrieving multiple ResultSets from SqlDataReader we use the NextResult() method of the
SqlDataReader.
sqlReader.NextResult();
In the following source code you can see how to get multiple result sets from SqlDataReader() .

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
string sql = null;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";


sql = "Select top 2 * from product; select top 2 * from ordermaster; select top 2 * from orderdetails";

sqlCnn = new SqlConnection(connetionString);


try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
MessageBox.Show ("From first SQL - " + sqlReader.GetValue(0) + " - " + sqlReader.GetValue(1));
}

sqlReader.NextResult();

while (sqlReader.Read())
{
MessageBox.Show("From second SQL - " + sqlReader.GetValue(0) + " - " + sqlReader.GetValue(1));
}

sqlReader.NextResult();

while (sqlReader.Read())
{
MessageBox.Show("From third SQL - " + sqlReader.GetValue(0) + " - " + sqlReader.GetValue(1));
}

sqlReader.Close();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# Table Schema from SqlDataReader

The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not
update the data. When the ExecuteReader method in C# SqlCommand Object execute , it will instantiate a SqlClient.SqlDataReader
Object.
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
While SqlDataReader is open, you can retrieve the schema information about the current result set using the GetSchemaTable method of
SqlDataReader. GetSchemaTable returns a DataTable object, which populated with rows and columns that contain the schema
information for the current result set.

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
string sql = null;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";


sql = "Select * from product";

sqlCnn = new SqlConnection(connetionString);


try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
DataTable schemaTable = sqlReader.GetSchemaTable();

foreach (DataRow row in schemaTable.Rows)


{
foreach (DataColumn column in schemaTable.Columns)
{
MessageBox.Show (string.Format("{0} = {1}", column.ColumnName, row[column]));
}
}
sqlReader.Close();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# Table Schema from OleDbDataReader

The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not
update the data. When the ExecuteReader method in oledbCmd Object execute , it will instantiate an OleDb.OleDbDataReader Object in
C#.
OleDbDataReader oledbReader = oledbCmd.ExecuteReader();
While an OleDbDataReader is open, you can retrieve schema information about the current result set using the GetSchemaTable() .
GetSchemaTable returns a DataTable object populated with rows and columns that contain the schema information for the current result
set.

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbCommand oledbCmd ;
string sql = null;

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";


sql = "Your SQL Statement Here like Select * from product";

oledbCnn = new OleDbConnection(connetionString);


try
{
oledbCnn.Open();
oledbCmd = new OleDbCommand(sql, oledbCnn);
OleDbDataReader oledbReader = oledbCmd.ExecuteReader();
DataTable schemaTable = oledbReader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
foreach (DataColumn column in schemaTable.Columns)
{
MessageBox.Show (string.Format("{0} = {1}", column.ColumnName, row[column]));
}
}
oledbReader.Close();
oledbCmd.Dispose();
oledbCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET DataAdapter

DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the communication between the Dataset and the
Datasource. We can use the DataAdapter in combination with the DataSet Object. DataAdapter provides this combination by mapping Fill
method, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source
to match the data in the DataSet. That is, these two objects combine to enable both data access and data manipulation capabilities.

The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the Data Source. The Insert , Update and Delete
SQL operations , we are using the continuation of the Select command perform by the DataAdapter. The SelectCommand property of the
DataAdapter is a Command Object that retrieves data from the data source. TheInsertCommand , UpdateCommand ,
and DeleteCommand properties of the DataAdapter are Command objects that manage updates to the data in the data source according to
modifications made to the data in the DataSet. From the following links describes how to use SqlDataAdapter and OleDbDataAdapter in
detail.
C# SqlDataAdapter
C# OleDbDataAdapter

C# ADO.NET SqlDataAdapter

SqlDataAdapter Class is a part of the C# ADO.NET Data Provider and it resides in the System.Data.SqlClient namespace.


SqlDataAdapter provides the communication between the Dataset and the SQL database. We can use SqlDataAdapter Object in
combination with Dataset Object. DataAdapter provides this combination by mapping Fill method, which changes the data in the DataSet
to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet.
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Fill(ds);
The SqlDataAdapter Object and DataSet objects are combine to perform both data access and data manipulation operations in the SQL
ServerDatabase. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it won't
directly affect the Database, until the user invoke the Update method in the SqlDataAdapter.

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";


sql = "Select * from product";

sqlCnn = new SqlConnection(connetionString);


try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET OleDbDataAdapter

The OleDbDataAdapter is a part of the C# ADO.NET Data Provider and it resides in the System.Data.OleDb namespace. The
OleDbDataAdapter provides the communication between the Dataset and the OleDb Data Sources. We can use OleDbDataAdapter Object
in combination with Dataset Object. DataAdapter provides this combination by mapping Fill method, which changes the data in the
DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet.
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
oledbAdapter.Fill(ds);
The OleDbDataAdapter Object and DataSet objects are combine to perform both Data Access and Data Manipulation operations in the
OleDb Data Sources. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it
won't directly affect the Database, until the user invoke the Update method in the OleDbDataAdapter.

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbDataAdapter oledbAdapter ;
DataSet ds = new DataSet();
string sql = null;
int i = 0;

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";


sql = "Your SQL Statement Here like Select * from product";

oledbCnn = new OleDbConnection(connetionString);


try
{
oledbCnn.Open();
oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
oledbAdapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
oledbAdapter.Dispose();
oledbCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

ExecuteReader and ExecuteNonQuery

ExecuteReader : ExecuteReader used for getting the query results as a DataReader object. It is readonly forward only retrieval of records
and it uses select command to read through the table from the first to the last.
SqlDataReader reader;
reader = Command.ExecuteReader();
while (reader.Read()) {
MessageBox.Show(reader.Item(0));
}
reader.Close();
ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements
like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
int retValue = 0;
Command = new SqlCommand(Sql, Connection);
retValue = Command.ExecuteNonQuery();

C# DataAdapater Tutorial

DataAdapter is a part of the ADO.NET Data Provider. DataAdapter is used to retrieve data from a data source and populate tables within
a DataSet. The DataAdapter also resolves changes made to the DataSet back to the data source. The Fill method uses the DataReader
object implicitly to return the column names and types used to create the tables in the DataSet, as well as the data to populate the rows of
the tables in the DataSet. Dataset represents a collection of data retrieved from the Data Source and saving data to the Data Source. We
can use Dataset in combination with DataAdapter class.
The DataAdapter uses the Connection object of the .NET Framework data provider to connect to a data source and Command objects to
retrieve data from and resolve changes to the data source. Each .NET Framework data provider included with the .NET Framework has a
DataAdapter object. The .NET Framework Data Provider for OLEDB includes anOleDbDataAdapter object, the .NET Framework Data
Provider for SQL Server includes a SqlDataAdapter object, and the .NET Framework Data Provider for ODBC includes
an OdbcDataAdapter object.
Functionally DataAdapter is the complex Object when compare to other Objects in the Data Provider . From the following links you can
learn more about DataAdapter in combination with dataset.

How to DataAdapter in Sql Server

SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . The
SqlConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the
data coming from. So the SqlDataAdapter manage the communication between these two Objects.
A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet. The DataAdapter also resolves changes
made to the DataSet back to the data source. We can use Fill method of the SqlDataAdapter for populating data in a Dataset. The
following c# source code shows a simple program that uses SqlDataAdapter to retrieve data from Data Source with the help of
SqlConnection Object and populate the data in a Dataset .

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try {
connection.Open();
adapter = new SqlDataAdapter("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) {
MessageBox.Show (ds.Tables[0].Rows[i].ItemArray[1].ToString());
}
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter in OLEDB

OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object .
The OleDbConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source
where the data coming from. So the OleDbDataAdapter manage the communication between these two Objects.
OleDbDataAdapter is used to retrieve data from a data source and populate tables within a DataSet . The OleDbDataAdapter also resolves
changes made to the DataSet back to the data source. The OleDbDataAdapter object allows us to populate Data Tables in a DataSet. We
can use Fill method of the OleDbDataAdapter for populating data in a Dataset. The following c# Source Code shows a simple program
that uses OleDbDataAdapter to retrieve data from Data Source with the help of OleDbConnection object and populate the data in a
Dataset.

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection connection ;
OleDbDataAdapter oledbAdapter ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter("select * from users", connection);
oledbAdapter.Fill(ds);
oledbAdapter.Dispose();
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i].ItemArray[0].ToString ());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
DataAdapter Select Command - Sql Server

SqlDataAdapter is a part of the ADO.NET Data Provider. SqlDataAdapter provides the communication between the Dataset and the
Data Source with the help of SqlConnection Object .The SqlDataAdapter works with the DataSet to provide a disconnected data retrieval
mechanism.
The SelectCommand property of the SqlDataAdapter is a Command object that retrieves data from the data source. The Fill method of
the DataAdapter is used to populate a DataSet with the results of the SelectCommand . Fill method takes as its arguments a DataSet to be
populated, and a DataTable object , or the name of the DataTable to be filled with the rows returned from the SelectCommand. The
following C# program shows the SqlDataAdapter using its SelectCommand property to retrieve the data from the Data Source.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[1].ItemArray[1].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

DataAdapter Select Command - Sql Server

OleDbDataAdapter is a part of the ADO.NET Data Provider. OleDbDataAdapter provides the communication between the Dataset and
the Data Source with the help of OleDbConnection Object . The OleDbDataAdapter works with the DataSet to provide a disconnected
data retrieval mechanism.
The SelectCommand property of the OleDbDataAdapter is a Command object that retrieves data from the data source. The Fill method
takes its arguments a DataSet to be populated, and a DataTable object, or the name of the DataTable to be filled with the rows returned
from the SelectCommand. The following C# program shows the OleDbDataAdapter using its SelectCommand property to retrieve the
data from the Data Source.
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection connection ;
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
try
{
connection.Open();
oledbAdapter.SelectCommand = new OleDbCommand("Your SQL Statement Here", connection);
oledbAdapter.Fill(ds);
oledbAdapter.Dispose();
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i].ItemArray[0].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter Insert Command - Sql Server

SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection
Object . InsertCommand, UpdateCommand , and DeleteCommand properties of the SqlDataAdapter are Command objects that
manage updates to the data in the data source according to modifications made to the data in the DataSet.
The InsertCommand in SqlDataAdapter Object manages to insert the data in the specified Data Source . The following C# Source Code
shows how to insert data in the Data Source using SqlDataAdapter and SqlCommand object. Open a connection to the Data Source with
the help of SqlConnection object and create a SqlCommand object with insert SQL statement, and assign the SqlCommand to the
SqlDataAdapter's InsertCommand.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "insert into product (Product_id,Product_name,Product_price) values(6,'Product6',600)";
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter Insert Command - OLEDB

OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection
Object .InsertCommand , UpdateCommand , and DeleteCommand properties of the OleDbDataAdapter are Command objects that
manage updates to the data in the data source according to modifications made to the data in the DataSet.
The InsertCommand in OleDbDataAdapter Object manages to insert the data in the specified Data Source . From the following C#
Source Code shows how to insert data in the Data Source using OleDbDataAdapter andOleDbCommand Object . Open a connection to
the Data Source with the help of OleDbConnection object and create an OleDbCommand object with insert SQL statement, and assign the
OleDbCommand to the SqlDataAdapter's InsertCommand.

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection connection ;
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
string sql = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
sql = "insert into user values('user1','password1')";
try
{
connection.Open();
oledbAdapter.InsertCommand = new OleDbCommand(sql, connection);
oledbAdapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row(s) Inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter Update Command - Sql Server

SqlDataAdapter is a part of the ADO.NET Data Provider. The SqlDataAdapter uses the Connection object of the .NET Framework data
provider to connect to a data source and Command objects to retrieve data from and resolve changes to the data source.
The InsertCommand , the UpdateCommand , and the DeleteCommand properties of the SqlDataAdapter Object update the database
with the data modifications, that are run on a DataSet object.
The following C# code samples demonstrate how to use the SqlDataAdapter object to update a SQL Server database
usingUpdateCommand properties .

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "update product set product_price = 1001 where Product_name ='Product6'";
try
{
connection.Open();
adapter.UpdateCommand = connection.CreateCommand();
adapter.UpdateCommand.CommandText = sql;
adapter.UpdateCommand.ExecuteNonQuery();
MessageBox.Show ("Row updated !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter Update Command - OLEDB


OleDbDataAdapter is a part of the ADO.NET Data Provider. The OleDbDataAdapter uses the Connection object of the .NET
Framework data provider to connect to a data source and Command objects to retrieve data from and resolve changes to the data source.
The InsertCommand , the UpdateCommand , and the DeleteCommand properties of the OleDbDataAdapter object update the Data
Source with the data modifications that are run on a DataSet object.
The following C# code samples demonstrate how to use the OleDbDataAdapter object to update an OLEDB Data Source
usingUpdateCommand properties .

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection connection ;
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
string sql = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
sql = "update Users set Password = 'new password' where UserID = 'user1'";
try
{
connection.Open();
oledbAdapter.UpdateCommand = connection.CreateCommand();
oledbAdapter.UpdateCommand.CommandText = sql;
oledbAdapter.UpdateCommand.ExecuteNonQuery();
MessageBox.Show ("Row(s) Updated !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter Delete Command - OLEDB

OleDbDataAdapter is a part of the ADO.NET Data Provider. The OleDbDataAdapter works with the DataSet to provide a disconnected
data retrieval mechanism. The OleDbDataAdapter uses the Connection object of the .NET Framework data provider to connect to a data
source and Command objects to retrieve data from and resolve changes to the data source.
InsertCommand , UpdateCommand , and DeleteCommand properties of the DataAdapter are Command objects that manage updates
to the data in the data source according to modifications made to the data in the DataSet. The following C# Source Code shows how to
perform delete data from a database using DeleteCommand property of OleDbDataAdapter.

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection connection ;
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
string sql = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
sql = "delete from tblusers1 where UserID = 'user1'";
try
{
connection.Open();
oledbAdapter.DeleteCommand = connection.CreateCommand();
oledbAdapter.DeleteCommand.CommandText = sql;
oledbAdapter.DeleteCommand.ExecuteNonQuery();
MessageBox.Show ("Row(s) Deleted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter CommandBuilder in Sql Server

The DataAdapter is a part of the ADO.NET Data Provider. ADO.NET DataAdapter is used to manage four separate Command objects.
TheInsertCommand , the UpdateCommand , and the DeleteCommandproperties of the SqlDataAdapter object update the database
with the data modifications that are run on a DataSet object. The SqlCommand objects that are assigned to these properties can be created
manually in code or automatically generated by using the SqlCommandBuilder object.
The SqlCommandBuilder opens the Connection associated with the DataAdapter and makes a round trip to the server each and every
time it's asked to construct the action queries. It closes the Connection when it's done. The following C# Source Code demonstrate how to
use the SqlDataAdapter object to update a SQL Server database with data modifications that are run on a DataSet Object that is
populated with data from a table in the database using SqlCommandBuilder object.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommandBuilder cmdBuilder ;
DataSet ds = new DataSet();
string sql = null;
Int32 i ;

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";


connection = new SqlConnection(connetionString);
sql = "select * from Product";
try
{
connection.Open();
adapter = new SqlDataAdapter(sql, connection);
cmdBuilder = new SqlCommandBuilder(adapter);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ds.Tables[0].Rows[i].ItemArray[2] = Convert.ToInt32 (ds.Tables[0].Rows[i].ItemArray[2]) + 100;
}
adapter.Update(ds.Tables[0]);
connection.Close();
MessageBox.Show ("Data updated ! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

}
}
}

How to DataAdapter CommandBuilder in OLEDB

The OleDbDataAdapter is a part of the ADO.NET Data Provider. OleDbDataAdapter is used to manage four separate Command objects.
The InsertCommand , the UpdateCommand , and the DeleteCommandproperties of the OleDbDataAdapter object update the database
with the data modifications that are run on a DataSet object. The OleDbCommand objects that are assigned to these properties can be
created manually in code or automatically generated by using the OleDbCommandBuilder object.
The OleDbCommandBuilder opens the Connection associated with the OleDbDataAdapter and makes a round trip to the server each and
every time it's asked to construct the action queries. It closes the Connection when it's done. The following C# Source Code demonstrate
how to use the OleDbDataAdapter object to update a OLEDB Data Source with data modifications that are run on a DataSet object that is
populated with data from a table in the database using OleDbCommandBuilder Object.

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection connection ;
OleDbDataAdapter oledbAdapter ;
OleDbCommandBuilder oledbCmdBuilder ;
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
sql = "select * from tblUsers";
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(sql, connection);
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
oledbAdapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ds.Tables[0].Rows[i].ItemArray[2] = "neweamil@email.com";
}
oledbAdapter.Update(ds.Tables[0]);
connection.Close();
MessageBox.Show ("Email address updates !");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter DataGridView - Sql Server

SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . The
SqlConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the
data is coming from. So the SqlDataAdapter manage the communication between these two Objects. The TableMapping Collections help
the SqlDataAdapter to do this task.
The InsertCommand , the UpdateCommand , and the DeleteCommandproperties of the SqlDataAdapter object update the database
with the data modifications that are run on a DataSet object. The following C# source code demonstrate how to update a Dataset through
SqlDataAdapter using a DataGridView . For running this C# source code , open a new C# project and drag two buttons and
a DataGridView in the default form1 and copy and paste the following Source Code.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
SqlConnection connection;
SqlDataAdapter adapter;
SqlCommandBuilder cmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
string Sql;
Int32 i;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
Sql = "select * from Product";
try
{
connection.Open();
adapter = new SqlDataAdapter(Sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

private void button2_Click(object sender, EventArgs e)


{
try
{
cmdBuilder = new SqlCommandBuilder(adapter);
changes = ds.GetChanges();
if (changes != null)
{
adapter.Update(changes);
}
MessageBox.Show("Changes Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to DataAdapter DataGridView - OLEDB

OleDbDataAdapter provides the communication between the Dataset and the OLEDB Data Source with the help of OleDbConnection
Object . The OleDbConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data
Source where the data coming from. So the OleDbDataAdapter manage the communication between these two Objects.
The TableMapping Collection help the OleDbDataAdapter to do this task.
The InsertCommand , the UpdateCommand , and the DeleteCommandproperties of the OleDbDataAdapter object update the database
with the data modifications that are run on a DataSet object. The following C# source code demonstrate how to update a Dataset through
OleDbDataAdapter using a DataGridView . For running this C# source code , open a new C# project and drag two buttons and
a DataGridViewin the default form1 and copy and paste the following Source Code.

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter;
OleDbCommandBuilder oledbCmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
int i;
string Sql;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
Sql = "select * from tblUsers";
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(Sql, connection);
oledbAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

private void button2_Click(object sender, EventArgs e)


{
try
{
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
changes = ds.GetChanges();
if (changes != null)
{
oledbAdapter.Update(ds.Tables[0]);
}
ds.AcceptChanges();
MessageBox.Show("Save changes");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

Csharp DataView Tutorial

The DataView provides different views of the data stored in a DataTable. That is we can customize the views of data from a DataTable.
DataView can be used to sort, filter, and search the data in a DataTable , additionally we can add new rows and modify the content in a
DataTable.
We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to
the DefaultView property of the DataTable. Note that if you create a DataView using the constructor that does not take any arguments,
you will not be able to use the DataView until you have set the Table property. In the following links you can see how to use DataView in
different ways in C# Language .

How to create a DataView

The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search in a DataTable ,
additionally we can add new rows and modify the content in a DataTable. DataViews can be created and configured both design time and
run time . Changes made to a DataView affect the underlying DataTable automatically, and changes made to the underlying DataTable
automatically affect any DataView objects that are viewing the DataTable. Using a DataView, you can expose the data in a table with
different sort orders, and you can filter the data by row state or based on a filter expression.
We can create DataView in two different ways. We can use the DataView Constructor , or you can create a reference to
the DefaultView Propertyof the DataTable. The DataView constructor can be empty, or it can take either a DataTable as a single
argument, or a DataTable along with filter criteria, sort criteria, and a row state filter.
dv = ds.Tables[0].DefaultView;
The following source code shows how to create a DataView in C#. Create a new C# project and drag a DataGridView and a Button on
default Form Form1 , and copy and paste the following C# Source Code on button click event.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Create DataView");
adapter.Dispose();
command.Dispose();
connection.Close();

dv = ds.Tables[0].DefaultView;

dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to Sort a DataView

The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search data in a
DataTable , additionally we can add new rows and modify the content in a DataTable. DataViews can be created and configured on both
design time and run time . Changes made to a DataView affect the underlying DataTableautomatically, and changes made to the
underlying DataTable automatically affect any DataView objects that are viewing that DataTable. More over a DataView provides a
dynamic view of data in the underlying DataTable: the content, ordering, and membership reflect changes as they occur.
We can sort single or multiple fields in a DataView , also we can specify the sort order like ASC (ascending) and DESC (descending) .
The following C# example creates a View and apply sort on the column Product_Price in descending order. Create a new C# project and
drag a DataGridView and a Button on default Form Form1 , and copy and paste the following C# Source Code on button click event.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Sort DataView");
adapter.Dispose();
command.Dispose();
connection.Close();

dv = new DataView(ds.Tables[0], "Product_Price > 3000", "Product_Price Desc", DataViewRowState.CurrentRows);

dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to Filter a DataView

DataView enables you to create different views of the data stored in a DataTable. That is we can customize the views of data from a
DataTable. DataView can be used to sort, filter, and search a DataTable , additionally we can add new rows and modify the content in
a DataTable . We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the
DefaultView property of the DataTable. Also we can create multiple DataViews for any given DataTable.
The following C# source code creates a view that shows all Product Details where the Product Price less than 3000. Create a new C#
project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following C# Source Code on button
click event.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Filter DataView");
adapter.Dispose();
command.Dispose();
connection.Close();

dv = new DataView(ds.Tables[0], "Product_Price < = 3000", "Product_Name", DataViewRowState.CurrentRows);

dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to Search in a DataView

The DataView provides different views of the data stored in a DataTable. The constructor for the DataView class initializes a new
instance of the DataView class and accepts the DataTable as an argument. We can create DataView in two ways. Either we can use
the DataView Constructor , or we can create a reference to the DefaultView property of the DataTable. We can create multiple
DataViews for any given DataTable.A DataView provides a dynamic view of data in the underlying DataTable: the content,ordering, and
membership reflect changes as they occur.
We can search in a DataView according to the sort key values by using the Find method . The Find method returns an integer with the
index of theDataRowView that matches the search criteria. If more than one row matches the search criteria, only the index of the first
matching DataRowView is returned. If no matches are found, Find returns -1
int index = dv.Find("PRODUCT5");

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Find Row DataView");
adapter.Dispose();
command.Dispose();
connection.Close();

dv = new DataView(ds.Tables[0]);
dv.Sort = "Product_Name";
int index = dv.Find("PRODUCT5");
if (index == -1)
{
MessageBox.Show ("Item Not Found");
}
else
{
MessageBox.Show(dv[index]["Product_id"].ToString() + " " + dv[index]["Product_Name"].ToString());

}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to add new row in a DataView

The DataView provides different views of the data stored in a DataTable. DataViews can be created and configured on both design time
and run time . We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to
the DefaultView Property of the DataTable. We can create multiple DataViews for any given DataTable. Note that if you create a
DataView using the constructor that does not take any arguments, you will not be able to use the DataView until you have set the Table
property.
We can add new rows in the DataView using AddNew method in the DataView. The following C# source code shows how to add new
row in a DataView . Create a new C# project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the
following C# Source Code on button click event.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Add New");
adapter.Dispose();
command.Dispose();
connection.Close();

dv = new DataView(ds.Tables[0]);
DataRowView newRow = dv.AddNew();
newRow["Product_ID"] = 7;
newRow["Product_Name"] = "Product 7";
newRow["Product_Price"] = 111;
newRow.EndEdit();
dv.Sort = "product_id";

dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to edit row in a DataView

The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search a DataTable ,
additionally we can add new rows and modify the content in a DataTable. We can create DataView in two ways. Either we can use
the DataView Constructor , or we can create a reference to the DefaultView property of the DataTable. Also we can create multiple
DataViews for any given DataTable. Using a DataView, you can expose the data in a table with different sort orders, and you can filter the
data by row state or based on a filter expression.
We can update the data in a DataView . The following C# source code shows how to update data in a DataView . Create a new C# project
and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following C# Source Code on button click event.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Update");
adapter.Dispose();
command.Dispose();
connection.Close();

dv = new DataView(ds.Tables[0], "", "Product_Name", DataViewRowState.CurrentRows);


int index = dv.Find("PRODUCT5");

if (index == -1)
{
MessageBox.Show ("Product not found");
}
else
{
dv[index]["Product_Name"] = "Product11";
MessageBox.Show("Product Updated !");
}

dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

How to delete row in a DataView

The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search data in a
DataTable , additionally we can add new rows and modify the content in a DataTable. A DataView enables you to create different views
of the data stored in aDataTable , a capability that is often used in data-binding applications.
A DataView provides a dynamic view of data in the underlying DataTable: the content, ordering, and membership reflect changes as they
occur. Also we can delete the data from the DataView . The following C# source code shows how to delete the data from DataView.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Delete Row");
adapter.Dispose();
command.Dispose();
connection.Close();

dv = new DataView(ds.Tables[0], "", "Product_ID", DataViewRowState.CurrentRows);


dv.Table.Rows[3].Delete();

dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to create a new DataTable from the DataView

The DataView provides different views of the data stored in a DataTable. That is we can customize the views of data from a DataTable.
Changes made to a DataView affect the underlying DataTable automatically, and changes made to the
underlying DataTable automatically affect any DataView objects that are viewing that DataTable. Note that if you create a DataView
using the constructor that does not take any arguments, you will not be able to use the DataView until you have set the Table property.
A DataView enables you to create different views of the data stored in a DataTable, a capability that is often used in data-binding
applications. We can create a new DataTable from the DataView . We can use the ToTable method to copy all the rows and columns, or a
subset of the data into a new DataTable .

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Copy to DataTable");
adapter.Dispose();
command.Dispose();
connection.Close();

dv = new DataView(ds.Tables[0], "Product_Price <= 2000", "Product_ID", DataViewRowState.CurrentRows);


DataTable dTable ;
dTable = dv.ToTable();

dataGridView1.DataSource = dTable;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

C# Remotable Object

Any object outside the application domain of the caller application should be considered as Remote Object . A Remote Object that
should be derived from MarshalByRefObject Class. Any object can be changed into a Remote Object by deriving it from
MarshalByRefObject . Objects without inheriting from MarshalByRefObject are called Non-remotable Objects.
The following example creating a Remote Object in C#, RemoteTime , which send the current time to the Client Application using
Remoting Framework. The RemoteTime class is derived from MarshalByRefObjectand inside the class it has a method getTime() which
returns the current time from the Remote Object.

using System;

public class RemoteTime : MarshalByRefObject


{
private string currentTime = "";

public string getTime()


{
currentTime = DateTime.Now.ToShortTimeString();
return "Remote Server Time : " + currentTime;
}
}

Copy and paste the above C# source code into a file and save it as RemoteTime.vb 
Compile the class RemoteTime.cs into a library using the command-line tools that shiped with theVisual Studio SDK . 

At the command prompt type the following command: 


csc /t:library RemoteTime.cs

After you compile the RemoteTime.cs , you will get a file called RemoteTime.dll in the directory where your compiler resides. 

If your file RemoteTime.cs is residing in c:\src then you should type command like the following : 
csc /t:library c:\src\RemoteTime.cs

C# Remote Listener Object

We already created a Remote Type Object C# Remotable Object in the previous section. We have to create a listener Object for enable
Objects in other application domains to create instances of this object (RemoteTime ) Remotely. When creating a listener Object we have
to choose and register a channel for handle the networking protocol and serialization formats and register the Type with the .NET
Remoting System , so that it can use the channel to listen for requests for the Type. C# Remote Channels are Objects that responsible of
handling the network protocols and serialization formats.
In the following C# source code we are creating a listener applicationTimeListener.cs . It will act as a listener Object for the Remote
Type RemoteTime. The Listener class TimeListener must be able to find the TimeListener.exe.config file to load the configuration for the
RemotableType class.

using System;
using System.Runtime.Remoting;

public class TimeListener


{
public static void Main()
{
RemotingConfiguration.Configure("TimeListener.exe.config");
Console.WriteLine("Listening for requests from the Client! Press Enter to exit...");
Console.ReadLine();
}
}

Copy and paste the above C# source code into a file and save it as TimeListener.cs . 
We have to create additional configuration file to provide the communication information to the listener Object. The configuration file is
an XML structured file. We can specify the Activation Mode , theRemote Type , Channel , port for communication etc. through the
configuration file . 
Click here to download TimeListener.exe.config 

Compile the class file TimeListener.cs using the command-line tools that ship with the Visual Studio SDK . 

At the command prompt type the following command: 


csc /r:RemoteTime.dll TimeListener.cs

After you compile the TimeListener.cs , you will get a file called TimeListener.exe in the directory where your compiler resides. 

If your file TimeListener.cs and RemoteTime.dll is residing in c:\src then you should type command like the following : 
csc /r:c:\src\RemoteTime.dll c:\src\TimeListener.cs

C# Remote Client Object

The Client application for calling Remote Object's method in C# is pretty simple and straight forward. The .NET Remoting System will
intercept the client calls, forward them to the remote object, and return the results to the client. The Client Application have to register for
the Remote Type also.
Here, in the Client application in C# , creating an instance of the Remote Type , RemoteTime Object , and call the method getTime() .
Additionally it uses the configuration file Client.exe.config for the communication information for the Remoting Framework.

using System;
using System.Runtime.Remoting;

public class Client


{
public static void Main()
{
RemotingConfiguration.Configure("Client.exe.config");
RemoteTime remoteTimeObject = new RemoteTime();
Console.WriteLine(remoteTimeObject.getTime());
}
}

Copy and paste the above C# source code into a file and save it as Client.cs . 
We have to create additional configuration file to provide the communication information to the Client Object . The configuration file is
a an XML structured file. We can specify the Remote Type , Channel , port for communication etc. through the configuration file . 
Click here to download Client.exe.config 

Compile the class file Client.cs using the command-line tools that ship with the Visual Studio SDK . 

At the command prompt type the following command: 


csc /r:RemoteTime.dll Client.cs

After you compile the Client.cs , you will get a file called Client.exe in the directory where your compiler resides. 

If your file Client.cs and RemoteTime.dll is residing in c:\src then you should type command like the following : 
csc /r:c:\src\RemoteTime.dll c:\src\Client.cs

How to run Remote Application

The .NET Remoting is one of several ways to establish communication between application domains using the .NET Framework.
The main three components of a Remoting Framework are a Remotable Object , Listener Application for listening requests for remote
object and a Client Application makes requests for remote object. Additionally you need Configuration files for your Listener Application
and Client Application .
How to compiling the C# source code files ?
Create a new folder SRC in c:\ and put the three C# source code files in that folder.
The files are :
1. C# Remotable Object
2. C# Remote Listener Application - (listening requests for Remote Object)
3. C# Remote Client Application - (makes requests for Remote Object)
Add the two configuration files in the same folder (c:\src).
1. download TimeListener.exe.config
2. download Client.exe.config
Now total of 5 files in your c:\src folder.
Compile each C# class files using the command-line tools separately that ship with the Visual Studio SDK .
csc /t:library RemoteTime.cs
csc /r:RemoteTime.dll TimeListener.cs
csc /r:RemoteTime.dll Client.cs
Note: You have to provide the physical path of each source files when you compile the source code , for example : if the source code files
are in the folder c:\SRC , you have to give path like
csc /t:library c:\src\RemoteTime.cs
csc /r:c:\src\RemoteTime.dll c:\src\TimeListener.vb
csc /r:c:\src\RemoteTime.dll c:\src\Client.cs
After you complied the C# source code files, you will get additional three files in the c:\src folder.
They are :
RemoteTime.dll
TimeListener.exe
Client.exe
Now total of 8 files in your c:\src folder.
How to run the Remoting Application ?
Create two new folders and give the name like Server and Client respectively in c:\src folder.
Copy RemoteTime.dll , TimeListener.exe and TimeListener.exe.config to the c:\src\server folder.
Copy RemoteTime.dll , Client.exe and Client.exe.config to the c:\src\client folder.
Open a command prompt on Server folder and type TimeListener
c:\src\server TimeListener
Then you will get a screen showing "Listening for requests from the Client. Press Enter to exit..."
Open a command prompt on Client folder and type Client.
c:\src\client Client
Then you will get the current time from Remote Object.
Now you have done your first .Net Remoting C# Project successfully . Try to explore more on Remoting ...

How to Remote Application Configuration

The .NET Remoting allows an application to make a Remotable Object available across remoting boundaries, which includes different
processes or even different computers connected by a network. By default the .NET Framework ships with two formatters(Binary
Formatter or SOAP Formatter ) and two channels(TcpChannel ,HttpChannel). Formatters and Channel are configured by using
Configuration files. It can be easily Configured by using XML-based files.
Configuration provides the necessary information to .Net Remoting Framework . We can provide .Net Remoting configuration
parameters in two ways. Either we can provide the information to the Server and the Client directly by program coding or through a
Machine.config file.
Using a configuration file is give better advantage over coding because the parameters of remote object can be configured without
changing any program coding and avoid recompile the source code.
Following are the information provided by configuration file :
1. Metadata describing the Remote Type
2. Type of Activation
3. Channels
4. The URL that uniquely identifies the object of that type.
Here we have to provide configuration information to Listener Object and also Client Object .
Listener Configuration

Click here to download TimeListener.exe.config


Client Configuration

Click here to download Client.exe.config

How to Remote Activation

The .Net Remoting Framework supports Server Activation and Client Activation of Remote Objects. Before an Object instance of a
Remotable type can be accessed, it must be created and initialized by Activation Process .
There are commonly two types of activation modes.
1. Server Activation mode
2. Client Activation mode
Server Activation mode is normally used when a Remote objects is not required to maintain any state between method calls. Client
Activationmode objects are instantiated from the client, and the client manages the lifetime of the Remote Object by using a lease-based
system provided for that purpose.
SingleCall Objects and Singleton Objects
SingleCall Objects and Singleton Objects belong to Server Activation mode. For SingleCall objects the server will create a single object,
execute the method, and destroy the object again. On the other hand with Singleton mode only one object is created at all. Singleton
objects can be used to share information between multiple clients.
The real distinction between Client Activated and Server ActivatedObject is that a Server-Activated Object is not really created when a
client instantiates it. Instead, it is created as needed.

How to Remoting Channels

The .Net Remoting Channels are used to transport messages to and from the Remote Objects. Channels are Objects that responsible of
handling the network protocols and serialization formats. In .Net, Remoting channel can be implement either by calling the method
ChannelServices.RegisterChannel or by using configuration file. Channels should be registered before Objects are registered.
When a channel is registered, it is automatically starts listening for client requests at the specified port. At least one channel must be
registered with the remoting framework before a Remote Object can be called.
There are two types of Channels available in .Net Remote Framework.
1. HTTP Channel
2. TCP Channel
The HTTP channel transports messages to and from remote objects using the SOAP Protocol . The TCP channel uses a binary formatter
to serialize all messages to a binary stream and transport the stream to the target URI using the TCP Protocol .

How to Remoting Formatters

Formatters are used for encoding and decoding the messages before they are transported by the Channel in .Net Remoting Framework.
The .Net Remoting Framework supports two types of Formatters
1. Binary Formatter - System.Runtime.Serialization.Formatters.Binary
2. SOAP Formatter - System.Runtime.Serialization.Formatters.Soap
The data in binary Formatter has smaller size when compared to SOAP Formatter. The SOAP Formatter is an XML based cross platform
text format , so it can be human readable. The data in a SOAP Formatter larger size when compared to Binary Formatter , so it can
therefore reduce overall performance.

C# XML Tutorial

XML is a self describing language and it gives the data as well as the rules to identify what information it contains.
Like HTML , XML is a subset of SGML - Standard Generalized Markup Language. The following links give you more information
about XML Files and its operations through C# Programming Language.

How to XML in C#

XML is a general purpose tag based language and very easy to transfer and store data across applications. Like HTML , XML is a subset
of SGML(Standard Generalized Markup Language). XML is a platform independent language, so the information formatted in XML can
be used in any other platforms (Operating Systems). XML is a self describing language and it gives the data as well as the rules to identify
what information it contains.
XML files are made up of tags that contains data. Generally a start tag and end tag to hold the data. For example, if you want to create an
XML tag name "Header" , the start tag is like < Header > and the end tag is like < /Header > . We can fill our information between these
tags.
< Header > Header Content Here < /Header >
While creating an XML file , some important points have to remember :
* XML is case sensitive
ex: < Header > is not same as < HeadeR > .
* Tags must be closed in the reverse order that they were opened
ex : < first-tag >< second-tag > Data here < /second-tag > < /first-tag >
Sample XML File
The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations
in XML formatted files . These classes are stored in the namespaces like System.Xml, System.Xml.Schema, System.Xml.Serialization,
System.Xml.XPath, System.Xml.Xsl etc. The Dataset in ADO.NET uses XML as its internal storage format.
You can use any text editor to create an XML file . More over XML files are readable by humans as well as computers. From the
following links you can see how to use XML in C# Programming Language.

How to create an XML file in C#

XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems).
Once we create an XML file in one platform it can be used in other platforms also.
In order to creating a new XML file in C#, we are using XmlTextWriter Class . The class takes FileName and Encoding as argument.
Also we are here passing formatting details . The following C# source code creating an XML file product.xml and add four rows in the
file.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
XmlTextWriter writer = new XmlTextWriter("product.xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.WriteStartElement("Table");
createNode("1", "Product 1", "1000", writer);
createNode("2", "Product 2", "2000", writer);
createNode("3", "Product 3", "3000", writer);
createNode("4", "Product 4", "4000", writer);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
MessageBox.Show("XML File created ! ");
}

private void createNode(string pID, string pName, string pPrice, XmlTextWriter writer)
{
writer.WriteStartElement("Product");
writer.WriteStartElement("Product_id");
writer.WriteString(pID);
writer.WriteEndElement();
writer.WriteStartElement("Product_name");
writer.WriteString(pName);
writer.WriteEndElement();
writer.WriteStartElement("Product_price");
writer.WriteString(pPrice);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}

Output of the above source code : 


How to open and read an XML file in C#

XML is a self describing language and it gives the data as well as the rules to extract what data it contains. Reading an XML file means
that we are reading the information embedded in XML tags in an XML file.
In the previous program we create an XML file and named it as products.xml. The following C# program read that file and extract the
contents inside the XML tag. We can read an XML file in several ways depends on our requirement. This program read the content in
Node wise . Here we are using XmlDataDocument Class to read the XML file . In this program it search the Node and its child Nodes
and extract the data in child nodes.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode ;
int i = 0;
string str = null;
FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("Product");
for (i = 0; i <= xmlnode.Count - 1; i++)
{
xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " | " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " | " +
xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
MessageBox.Show (str);
}
}
}
}
Click here to download the input file : product.xml 

How to create XML file from Dataset

XML is a tag based language, that means the document is made up of XML tags that contain information. We can create an XML file in
several ways.
In the previous section we created an XML file using XmlTextWriter Class. Here we are creating an XML file Product.XML using an
ADO.NET Dataset. In order to create this, we have to manually create a Datatable first and add the data of Product.XML in the Datatable .
Then add the Datatable in a Dataset . Call the method WriteXml of Dataset and pass the file name Product.XML as argument.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
DataTable dt;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
DataSet ds = new DataSet();
dt = new DataTable();
dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32")));
fillRows(1, "product1", 1111);
fillRows(2, "product2", 2222);
fillRows(3, "product3", 3333);
fillRows(4, "product4", 4444);
ds.Tables.Add(dt);
ds.Tables[0].TableName = "product";
ds.WriteXml("Product.xml");
MessageBox .Show ("Done");
}

private void fillRows(int pID, string pName, int pPrice)


{
DataRow dr ;
dr = dt.NewRow();
dr["Product_ID"] = pID;
dr["Product_Name"] = pName;
dr["product_Price"] = pPrice;
dt.Rows.Add(dr);
}
}
}

How to Open and read an XML file to Dataset

XML is a platform independent language, so the information formatted in XML can be use in any other platforms (Operating Systems) .
The .Net technology is widely supported XML file format. The .Net Frameworkprovides the Classes for read, write, and other operations
in XML formatted files .
In the previous section we already saw how to read an XML file through Node navigation . Here we are going to read an XML file using a
DataSet. Here Dataset is using an XmlReader for read the content of the file. Locate the XML file using XmlReader and pass the
XmlReader as argument of Dataset.
Click here to download the input file product.xml : product.xml

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
XmlReader xmlFile ;
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
int i = 0;
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[2].ToString());
}
}
}
}

How to create an XML file from SQL

XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely
supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .
Moreover the Dataset in ADO.NET uses XML format as its internal storage format.
There are several ways to create an XML file . In the previous sections we already saw how to create an XML file using XmlTextWriter
and also created an XML file using manually created Dataset. Here we are going to create an XML file from Database. Make an SQL
connection to the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml() method and pass the file name as
argument.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection );
SqlDataAdapter adapter ;
DataSet ds = new DataSet();
string sql = null;

connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password";


connection = new SqlConnection(connetionString);
sql = "select * from Product";
try
{
connection.Open();
adapter = new SqlDataAdapter(sql, connection);
adapter.Fill(ds);
connection.Close();
ds.WriteXml("Product.xml");
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());

}
}
}
}

You have to pass necessary database connection information to connection string. 

How to search in a XML file

XML files are made up of tags that contains information. The .Net technology is widely supported XML file format. Also the Dataset
inADO.NET uses XML format as its internal storage format.
The following C# source code shows how to search an item in a XML file using Dataset . Here Dataset using an XmlReader for read the
content of the file. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. By using the Dataset , search
the product Product2 in the file Product.XML with the help of DataView.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
XmlReader xmlFile ;
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
DataView dv ;
ds.ReadXml(xmlFile);

dv = new DataView(ds.Tables[0]);
dv.Sort = "Product_Name";
int index = dv.Find("Product2");

if (index == -1)
{
MessageBox.Show ("Item Not Found");
}
else
{
MessageBox.Show(dv[index]["Product_Name"].ToString() + " " + dv[index]["Product_Price"].ToString());

}
}
}
}

Click here to download the input file product.xml : product.xml 

How to filter in a XML file

XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems).
Once we create an XML file in one platform it can be used in other platforms also. The .Net technology is widely supported XML file
format. Also the Dataset in ADO.NET uses XML format as its internal storage format.
Here we are going to filter an XML file content and store the result in a newly created XML file through C#. We have an XML file
Product.XML , and it has a field Product_Price. We are giving a search criteria like theProduct_Price >= 3000 and store the result in a
newly created XML fileResult.XML .

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
XmlReader xmlFile ;
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
DataView dv ;
ds.ReadXml(xmlFile);
dv = new DataView(ds.Tables[0], "Product_price > = 3000", "Product_Name", DataViewRowState.CurrentRows);
dv.ToTable().WriteXml("Result.xml");
MessageBox.Show ("Done");
}
}
}

You can see the filter result in Result.xml file 


Click here to download the input file product.xml : product.xml

How to insert data from XML to database

XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely
supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .
Moreover the Dataset in ADO.NET uses XML format as its internal storage format.
Here we are going to insert the values of an XML file to a Database Table using SQL Insert Command . Here the Dataset using an
XmlReader for read the content of the XML file - Product.XML . Locate the XML file using XmlReader and pass the XmlReader as
argument of Dataset. Also establish a connection to the Database using a connectionstring . After getting the data from XML file to
the Dataset , we can loop through the dataset values and use insert command to add the values to the Product table in the Databse.
using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile ;
string sql = null;

int product_ID = 0;
string Product_Name = null;
double product_Price = 0;

connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password";

connection = new SqlConnection(connetionString);

xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());


ds.ReadXml(xmlFile);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
product_ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
Product_Name = ds.Tables[0].Rows[i].ItemArray[1].ToString();
product_Price = Convert.ToDouble(ds.Tables[0].Rows[i].ItemArray[2]);
sql = "insert into Product values(" + product_ID + ",'" + Product_Name + "'," + product_Price + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
connection.Close();
MessageBox.Show("Done .. ");
}
}
}

You have to pass necessary database connection information to connection string. 


Click here to download the input file product.xml : product.xml

How to create Excel file from XML

XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems).
XML is a self describing language and it gives the data as well as the rules to identify what the data it contains.
Here we are going to read from an XML file content and write the same content to an Excel file. Here using an XmlReader for read the
XML file to the Dataset . Loop through the Dataset and add the content to the Excel file . For create an excel file you have to add
reference of Excel library to you project , follow the link C# Create Excel File for details.
using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

DataSet ds = new DataSet();


XmlReader xmlFile ;
int i = 0;
int j = 0;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());


ds.ReadXml(xmlFile);

for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)


{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = ds.Tables[0].Rows[i].ItemArray[j].ToString ();
}
}

xlWorkBook.SaveAs("Specify path here\\xml2excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue,


misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);

MessageBox.Show("Done .. ");
}

private void releaseObject(object obj)


{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
}
}

Click here to download the input file product.xml : product.xml 

How to create XML file from Excel

XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net Framework provides
the Classes for read, write, and other operations in XML formatted files .
The following C# program shows how to create an XML file from an Excel file content . Here we are using an OleDbConnection to read
the excel file and store the content to a Dataset . Call the method WriteXml of Dataset to write to the XML file.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.DataSet ds ;
System.Data.OleDb.OleDbDataAdapter MyCommand ;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='Specify path
here \\xl2xml.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Product");
ds = new System.Data.DataSet();
MyCommand.Fill(ds);
MyConnection.Close();
ds.WriteXml("Product.xml");
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

}
}

Click here to download the input excel file xl2xml.xls 


How to XML to DataGridView

XML is a platform independent language, so the information formatted in XML file can be use in any other platforms . The .Net
technology is widely supported XML file format.
The following C# source code shows , how to load data in aDataGridView from an XML file . Here the Dataset using an XmlReader for
read the content of the XML file - Product.XML . Locate the XML file usingXmlReader and pass the XmlReader as argument of Dataset.
When the Dataset retrieves the data, it passes as DataSource to DataGridView .

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
XmlReader xmlFile ;
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

}
}

Click here to download the input file product.xml 

How to create a TreeView from XML File

XML is a self describing language and it gives the data as well as the rules to extract what the data it contains. Reading an XML file
means that we are reading the data embedded in tags in an XML file.
In the previous example we already saw how to read an XML file Node wise. Here we are reading XML file as Node and pass the Nodes
data toTreeView .

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNode xmlnode ;
FileStream fs = new FileStream("tree.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.ChildNodes[1];
treeView1.Nodes.Clear();
treeView1.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name));
TreeNode tNode ;
tNode = treeView1.Nodes[0];
AddNode(xmlnode, tNode);
}

private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)


{
XmlNode xNode ;
TreeNode tNode ;
XmlNodeList nodeList ;
int i = 0;
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for (i = 0; i <= nodeList.Count - 1; i++)
{
xNode = inXmlNode.ChildNodes[i];
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(xNode, tNode);
}
}
else
{
inTreeNode.Text = inXmlNode.InnerText.ToString();
}
}
}
}

Click here to download the input file tree.xml 

XML Serialization

Serialization of XML to Common Language Runtime Objects enables one to convert XML documents into a form where they are easier
to process using conventional programming languages. The .Net technology is widely supported XML file format. The .Net Framework
provides the Classes for read, write, and other operations in XML formatted files .
The following C# program shows how to serialize a Dataset to an XML disk file . Here we are using XmlSerializer Class for serialize the
Dataset Object.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml.Serialization ;
using System.IO;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
DataTable dt;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
DataSet ds = new DataSet();
dt = new DataTable();
dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32")));
fillRows(1, "product1", 9999);
fillRows(2, "product2", 2222);
fillRows(3, "product3", 3333);
fillRows(4, "product4", 4444);
ds.Tables.Add(dt);
ds.Tables[0].TableName = "product";

StreamWriter serialWriter ;
serialWriter = new StreamWriter("serialXML.xml");
XmlSerializer xmlWriter = new XmlSerializer(ds.GetType());
xmlWriter.Serialize(serialWriter, ds);
serialWriter.Close();
ds.Clear();
}
private void fillRows(int pID, string pName, int pPrice)
{
DataRow dr ;
dr = dt.NewRow();
dr["Product_ID"] = pID;
dr["Product_Name"] = pName;
dr["product_Price"] = pPrice;
dt.Rows.Add(dr);
}
}
}

Click here to download serialXML.xml 

XML DeSerialization

XML is a general purpose tag based language and very easy to transfer and store data across applications. XML Serialization is the
process of serializing a .Net Object to the form of XML file or from an XML to .Net Object.
During XML serialization, only the public properties and fields of an object are serialized. The following C# source code shows how
to De-Serializethe DataSet as it is streamed from an XML file back into memory.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml.Serialization ;
using System.IO;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
DataSet ds = new DataSet();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
FileStream readStream = new FileStream("serialXML.xml", FileMode.Open);
ds = (DataSet)xmlSerializer.Deserialize(readStream);
readStream.Close();
dataGridView1.DataSource = ds.Tables[0];
}

}
}

Click here to download serialXML.xml 

C# DataGridView Tutorial

In this tutorial, you will learn how to use the DataGridView control and its supporting classes, in detail. Displaying data in a tabular
format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete solution for displaying
tabular data with Windows Forms. The DataGridView control is highly configurable and extensible, and it provides many properties,
methods, and events to customize its appearance and behavior.
The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of cell values. The cell is the
fundamental unit of interaction for the DataGridView. All cells derive from the DataGridViewCell base class. Each cell within the
DataGridView control can have its own style, such as text format, background color, foreground color, and font. Typically, however,
multiple cells will share particular style characteristics. The data type for the cell's Value property by default is of type Object.
The following chapters explain the basics of DataGridView control and steps through an example that builds simple C# programs. All the
source code in the following examples ,we chose the Pubs database, which comes with SQL Server , as our target database.

C# DataGridView Binding - SQL Server dataset

The DataGridView can display data in Bound mode, unbound mode and Virtual mode . Bound mode is suitable for managing data using
automatic interaction with the data store. One very common use of the DataGridView control is binding to a table in a database. Unbound
mode is suitable for displaying relatively small amounts of data that you manage programmatically. Virtual mode gives you a higher
degree of control by allowing you to wait until a cell is actually being displayed to provide the value it will contain.
The following C# program shows how to bind a SQL Server dataset to a DataGridView.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}

DataGridView Binding - OLEDB dataset

The DataGridView can display data in Bound mode and unbound mode and Virtual mode. The easiest way to get started using the
DataGridView control is to use it in basic data-binding scenarios. When you specify a data source for the DataGridView, by default it will
construct columns for you automatically. This will be created based on the data types in the data source.
The following C# program shows how to bind an OLEDB dataset to a DataGridView.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your .mdb file;";
string sql = "SELECT * FROM Authors";
OleDbConnection connection = new OleDbConnection(connetionString);
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}

C# DataGridView Sorting and Filtering

The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its
appearance and behavior. A DataView provides a means to filter and sort data within a DataTable. The following C# program shows how
to filter and sort a DataGridView by using a DataView.
dv = new DataView(ds.Tables[0], "Price > 19", "Price Desc", DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Titles";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Titles_table");
connection.Close();

DataView dv;
dv = new DataView(ds.Tables[0], "Price > 19", "Price Desc", DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;
}
}
}

C# DataGridView Add Columns and Rows

The DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms. The DataGridView
control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and
behavior. All cells in a DataGridView control derive from the DataGridViewCell base class.
You can access the DataGridView control's columns by using the Columns collection and DataGridView control's rows by using the
Rows collection. The following C# source code shows how to manually
create Columns and Rows in a DataGridView.
dataGridView1.Columns[Index].Name = "Column Name";

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";

string[] row = new string[] { "1", "Product 1", "1000" };


dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);
}
}
}

C# DataGridView Hide Columns and Rows

Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete
solution for displaying tabular data with Windows Forms . The DataGridView control is highly configurable and extensible, and it
provides many properties, methods, and events to customize its appearance and behavior.
The following C# source code manually creates a DataGridView columns and rows and hide the second column and second row.
dataGridView1.Rows[Index].Visible = false;
dataGridView1.Columns[Index].Visible = false;

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";

string[] row = new string[] { "1", "Product 1", "1000" };


dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);

dataGridView1.Columns[1].Visible = false;
dataGridView1.Rows[1].Visible = false;

}
}
}

C# DataGridView Read Only Columns and Rows

The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data.
The ReadOnly property indicates whether the data displayed by the cell can be edited or not. You can set ReadOnly Property in three
levels. You can make entire dataGridView or entire column or entire row as ReadOnly .
dataGridView1.ReadOnly = true;
dataGridView1.Rows[index].ReadOnly = true;
dataGridView1.Columns[index].ReadOnly = true;
The following C# source code shows how to make a row as Readonly in a DataGridView.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";

string[] row = new string[] { "1", "Product 1", "1000" };


dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);

dataGridView1.Rows[1].ReadOnly = true;
}
}
}

Add Button to C# DataGridView

The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular
data.The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize
its appearance and behavior. The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with
the corresponding cell types.
The following C# program shows how to add a Button in Cell of a DataGridView control. Also it showing in the
dataGridView1_CellClick event which button the user clicked.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";

string[] row = new string[] { "1", "Product 1", "1000" };


dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);

DataGridViewButtonColumn btn = new DataGridViewButtonColumn();


dataGridView1.Columns.Add(btn);
btn.HeaderText = "Click Data";
btn.Text = "Click Here";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)


{
if (e.ColumnIndex == 3)
{
MessageBox.Show((e.RowIndex+1) + " Row " + (e.ColumnIndex+1) + " Column button clicked ");
}
}

}
}

Add CheckBox to C# DataGridView


The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data.
The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types.
While adding a CheckBox in a cell, the cell Value property can be set explicitly through programmatic code that accesses the cell in the
Cells collection of the row, or it can be set through data binding.
The following C# program shows how to add a CheckBox in Cell of a DataGridView control and set the third row checkbox value as true.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";

string[] row = new string[] { "1", "Product 1", "1000" };


dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);

DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();


dataGridView1.Columns.Add(chk);
chk.HeaderText = "Check Data";
chk.Name = "chk";
dataGridView1.Rows[2].Cells[3].Value = true;
}
}
}

Add ComboBox to C# DataGridView

Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete
solution for displaying tabular data with Windows Forms . The DataGridView control provides TextBox, CheckBox, Image, Button,
ComboBox and Link columns with the corresponding cell types.
The following C# program shows how to add a ComboBox in Cell of a DataGridView control.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";

string[] row = new string[] { "1", "Product 1", "1000" };


dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);

DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();


cmb.HeaderText = "Select Data";
cmb.Name = "cmb";
cmb.MaxDropDownItems = 4;
cmb.Items.Add("True");
cmb.Items.Add("False");
dataGridView1.Columns.Add(cmb);

}
}
}

Add Image to C# DataGridView

The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data.
We can add an Image control in a column of DataGridView. This column type exposes Image and ImageLayout properties in addition to
the usual base class properties. Setting the column Image property results in that image being displayed by default for all the cells in that
column. The following C# program shows how to add a Image in column of a DataGridView control.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";

string[] row = new string[] { "1", "Product 1", "1000" };


dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);

DataGridViewImageColumn img = new DataGridViewImageColumn();


Image image = Image.FromFile("Image Path");
img.Image = image;
dataGridView1.Columns.Add(img);
img.HeaderText = "Image";
img.Name = "img";

}
}
}

Add ViewLink to C# DataGridView

The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data.
The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types.
We can add hyperlink in the column of a DataGridView , the column type contains cells of type DataGridViewLinkCell and renders the
text in the cell to look like a hyperlink. The following C# program shows how to add a hyperlink in a column of DataGridView control.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";

string[] row = new string[] { "1", "Product 1", "1000" };


dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);

DataGridViewLinkColumn lnk = new DataGridViewLinkColumn();


dataGridView1.Columns.Add(lnk);
lnk.HeaderText = "Link Data";
lnk.Name = "Http://csharp.net-informations.com";
lnk.Text = "Http://csharp.net-informations.com";
lnk.UseColumnTextForLinkValue = true;

}
}
}

C# DataGridView Paging

The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data.
The cell is the fundamental unit of interaction for the DataGridView. All cells derive from the DataGridViewCell base class. Each cell
within the DataGridView control can have its own style, such as text format, background color, foreground color, and font. If the
DataGridView has lot of rows we can implement paging functionalities to the DataGridView control.
While we implement paging we should know the boundaries of the pages to enable the paging in the DatagridView. The following C#
program provides a way to programatically implement paging in a Windows Datagrid View control. Here the DataGridView rows fixed as
five rows and other two buttons are there for implementing paging functionalities.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlDataAdapter pagingAdapter;
DataSet pagingDS;
int scrollVal;

public Form1()
{
InitializeComponent();
scrollVal = 0;
}

private void button1_Click(object sender, EventArgs e)


{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
pagingAdapter = new SqlDataAdapter(sql, connection);
pagingDS = new DataSet();
connection.Open();
pagingAdapter.Fill(pagingDS, scrollVal, 5, "Authors_table");
connection.Close();
dataGridView1.DataSource = pagingDS;
dataGridView1.DataMember = "Authors_table";
}

private void button2_Click(object sender, EventArgs e)


{
scrollVal = scrollVal - 5;
if (scrollVal < = 0)
{
scrollVal = 0;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table");
}

private void button3_Click(object sender, EventArgs e)


{
scrollVal = scrollVal + 5;
if (scrollVal > 23)
{
scrollVal = 18;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table");
}
}
}

C# DataGridView Formatting

The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its
appearance and behavior. The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of
cell values.
Each cell within the DataGridView control can have its own style, such as text format, background color, foreground color, and font.
Typically, however, multiple cells will share particular style characteristics. You can define appearance and formatting styles for
individual cells, for cells in specific columns and rows, or for all cells in the control by setting the properties of the
DataGridViewCellStyle objects accessed through various DataGridView control properties.
The following C# program shows how to implement different ways of formatting in a DataGridView control.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Author_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Author_table";

dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque;
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;

dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;

dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.AllowUserToResizeColumns = false;
}
}
}

C# DataGridView Template
The DataGridView control makes it easy to define the basic appearance and the display formatting of rows and columns. There are
situations that you want greater control over the appearance of DataGridView rows than what is provided by the various DataGridView
cell style properties.
The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides.
With the row template, you can set any DataGridViewRow properties, including DefaultCellStyle. The following C# example illustrates
how to use the row template to specify an initial row height and a minimum row height and BackColor.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
DataGridViewRow row = this.dataGridView1.RowTemplate;
row.DefaultCellStyle.BackColor = Color.Bisque;
row.Height = 35;
row.MinimumHeight = 20;

string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";


string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Author_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Author_table";
}
}
}

C# DataGridView Printing

The DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms. The DataGridView
control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and
behavior. Unfortunately the DataGridView doesn't have a built in printing functionality . So here we do a tricky way to print the content of
DataGridView .
Here we add a PrintDocument object to the project and handle the PrintPage event which is called every time a new page is to be printed.
Here in the PrintPage event we create a Bitmap Object and draw the DataGridView to the Bitmap Object. In order to run this C# project
you have to drag two buttons ,one for load data and one for print command, and drag a PrintDocument control on your form . The
following picture shows how to drag PrintDocument Object to your project.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Author_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Author_table";

private void button2_Click(object sender, EventArgs e)


{
printDocument1.Print();
}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)


{
Bitmap bm = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
dataGridView1.DrawToBitmap(bm, new Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height));
e.Graphics.DrawImage(bm, 0, 0);
}

}
}

C# DataGridView Export to Excel

Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete
solution for displaying tabular data with Windows Forms. The DataGridView control is highly configurable and extensible, and it
provides many properties, methods, and events to customize its appearance and behavior. The following C# source code shows how to
Export the content of a datagridview to an Excel file.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}

private void button2_Click(object sender, EventArgs e)


{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;

xlApp = new Excel.ApplicationClass();


xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

for (i = 0; i <= dataGridView1.RowCount - 2; i++)


{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
}
}

xlWorkBook.SaveAs(@"c:\csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue,


misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}

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();
}
}
}
}

C# DataGridView Loading data from Excel

The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data.
The following C# source code shows how to Import data from an Excel file to a DataGridView control .

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-
informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
}
}

C# DataGridView Database Operations

The DataGridView can display data in Bound mode, unbound mode and Virtual mode . Bound mode is suitable for managing data using
automatic interaction with the data store. One very common use of the DataGridView control is binding to a table in a database. Unbound
mode is suitable for displaying relatively small amounts of data that you manage programmatically. Virtual mode gives you a higher
degree of control by allowing you to wait until a cell is actually being displayed to provide the value it will contain.
The following C# source code illustrate how to connect a DataGridView to a database and new/update or delete the database values from
DataGridView.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlCommand sCommand;
SqlDataAdapter sAdapter;
SqlCommandBuilder sBuilder;
DataSet sDs;
DataTable sTable;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Stores";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
sCommand = new SqlCommand(sql, connection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Stores");
sTable = sDs.Tables["Stores"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["Stores"];
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}

private void new_btn_Click(object sender, EventArgs e)


{
dataGridView1.ReadOnly = false;
save_btn.Enabled = true;
new_btn.Enabled = false;
delete_btn.Enabled = false;
}

private void delete_btn_Click(object sender, EventArgs e)


{
if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}

private void save_btn_Click(object sender, EventArgs e)


{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
}
}

pública :

público es el especificador de acceso más comunes en C #. Puede ser acceso desde cualquier lugar , eso significa que no hay ninguna
restricción sobre la accesibilidad . El ámbito de aplicación de la accesibilidad está dentro de clase como en el exterior . El tipo o miembro
puede tener acceso a cualquier otro código del mismo ensamblado o en otro conjunto que hace referencia a ella .

privada:
El ámbito de aplicación de la accesibilidad está limitada sólo dentro de las clases o estructura en la que se han declarado. Los miembros
privados no son accesibles fuera de la clase y es el nivel de acceso menos permisiva .

protegida :

El ámbito de la accesibilidad es limitada dentro de la clase o estructura y la clase derivada (heredado ) de esta clase.

interno :

Los modificadores de acceso internos pueden acceder dentro del programa que contiene sus declaraciones y también el acceso dentro del
mismo nivel de ensamblado , pero no a partir de otro conjunto .

protected internal :

Protegida interna es los mismos niveles de acceso de tanto protegida e internos . Se puede acceder a cualquier parte de la misma reunión y
en la misma clase también las clases heredan de la misma clase.

How to find date difference in C#

A date and time format string defines the text representation of a DateTime value that results from a formatting operation. In C# by calling
any of the overloads of the DateTime constructor that allow you to specify specific elements of the date and time value like year , month
or day.
DateTime newDate = new DateTime(2000, 5, 1);
Here newDate represents year as 2000 and month as May and date as 1 .
A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. Instead, the calculation
returns a new DateTime structure whose value is the result of the calculation. The DateTime.Substract method may be used in order to
find the date-time difference between two instances of the DateTime method.
System.TimeSpan diff = secondDate.Subtract(firstDate);
You can also find the difference between two dates using the following method.
String diff2 = (secondDate - firstDate).TotalDays.ToString();

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
System.DateTime firstDate = new System.DateTime(2000, 01, 01);
System.DateTime secondDate = new System.DateTime(2000, 05, 31);

System.TimeSpan diff = secondDate.Subtract(firstDate);


System.TimeSpan diff1 = secondDate - firstDate;

String diff2 = (secondDate - firstDate).TotalDays.ToString();

MessageBox.Show(diff1.ToString ());
}
}
}

How to use Enum in C#

If you have a number of constants that are logically related to each other, then you can group together these constants in an enumeration.
Syntax:
Enum declaration

enum Tempurature
{
Low,
Medium,
High,
};
Enums are strongly typed constants which makes the code more readable and less prone to errors. It is useful when you have a set of
values that are functionally significant and unchanged. The main advantage of Enum is make it easy to change values in the future, also
you can reduces errors caused by transposing or mistyping numbers.
Retrieve and check the Enum value

Temperature value = Tempurature.Medium;


if (value == Tempurature.Medium)
{
Console.WriteLine("Temperature is Mediuam..");
}

A simple Enum Exercise

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
enum Tempurature
{
Low,
Medium,
High,
};
private void button1_Click(object sender, EventArgs e)
{
Temperature value = Tempurature.Medium;
if (value == Tempurature.Medium)
{
MessageBox.Show ("Temperature is Mediuam..");
}
}
}
}
By default the underlying type of each element in the enum is int. If you try with above example to convert to integer then yo can see the
result like the following:

Temperature value = Tempurature.Medium;


int val = (int)value;
Console.WriteLine("Temperature value is.." + val);
Output is : Temperature value is..1
You can specify another integral numeric type by using a colon. The following Enum declare as byte, you can verify the underlying
numeric values by casting to the underlying type.

enum Temperature : byte


{
Low,
Medium,
High,
};
You can retrieve the value like the following:

Temperature value = Tempurature.Medium;


byte val = (byte)value;
Console.WriteLine("Temperature value is.." + val);
You can assign any values to the elements in the enumerator list of an enumeration type. By default, the first member of an enum takes the
value of zero. If this value doesn't make sense for your enum, you can change it to one or some other number. If you declare a different
value in the first member of Enum then it assign the next value greater by one than that of the immediately preceding member

enum Tempurature
{
Low = 2,
Medium,
High,
};
Temperature value = Tempurature.Medium;
int val = (int)value;
Console.WriteLine("Temperature value is.." + val);
Output is : Temperature value is.. 3
Enum in Switch Case
The following program shows how to use Enum in Switch..Case statement.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

enum Tempurature
{
Low,
Medium,
High,
};

private void button1_Click(object sender, EventArgs e)


{
Temperature value = Tempurature.Medium;
switch (value)
{
case Tempurature.Low:
MessageBox.Show("Low Tempurature");
break;
case Tempurature.Medium:
MessageBox.Show("Mediuam Tempurature");
break;
case Tempurature.High:
MessageBox.Show("High Tempurature");
break;
}

}
}
}

C# Label Control

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. The Label class is defined in the
System.Windows.Forms namespace.

Add a Label control to the form - Click Label in the Toolbox and drag it over the forms Designer and drop it in the desired location.
If you want to change the display text of the Label, you have to set a new text to the Text property of Label.
label1.Text = "This is my first Label";
In addition to displaying text, the Label control can also display an image using the Image property, or a combination of the ImageIndex
and ImageList properties.
label1.Image = Image.FromFile("C:\\testimage.jpg");
The following C# source code shows how to set some properties of the Label through coding.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
label1.Text = "This is my first Lable";
label1.BorderStyle = BorderStyle.FixedSingle;
label1.TextAlign = ContentAlignment.MiddleCenter;
}
}
}

C# ComboBox Control

C# controls are located in the Toolbox of the development environment, and you use them to create objects on a form with a simple series
of mouse clicks and dragging motions. A ComboBox displays a text box combined with a ListBox, which enables the user to select items
from the list or enter a new value .
The user can type a value in the text field or click the button to display a drop down list. You can add individual objects with the Add
method. You can delete items with the Remove method or clear the entire list with the Clear method.
comboBox1.Items.Add("Sunday");
If you want to retrieve the displayed item to a string variable , you can code like this
string var;
var = comboBox1.Text;
You can remove items from a combobox in two ways. You can remove item at a the specified index or giving a specified item by name.
comboBox1.Items.RemoveAt(1);
The above code will remove the second item from the combobox.
comboBox1.Items.Remove("Friday");
The above code will remove the item "Friday" from the combobox.
The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop-down. The
DropDownStyle property also specifies whether the text portion can be edited.
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
The following C# source code add seven days in a week to a combo box while load event of a Windows Form and int Button click event it
displays the selected text in the Combo Box.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
comboBox1.Items.Add("Sunday");
comboBox1.Items.Add("Monday");
comboBox1.Items.Add("Tuesday");
comboBox1.Items.Add("wednesday");
comboBox1.Items.Add("Thursday");
comboBox1.Items.Add("Friday");
comboBox1.Items.Add("Saturday");

}
private void button1_Click(object sender, EventArgs e)
{
string var;
var = comboBox1.Text;
MessageBox.Show(var);
}
}
}

C# ListBox Control

The ListBox control enables you to display a list of items to the user that the user can select by clicking.

In addition to display and selection functionality, the ListBox also provides features that enable you to efficiently add items to the ListBox
and to find text within the items of the list. You can use the Add or Insert method to add items to a list box. The Add method adds new
items at the end of an unsorted list box.
listBox1.Items.Add("Sunday");
If you want to retrieve a single selected item to a variable , you can code like this
string var;
var = listBox1.Text;
The SelectionMode property determines how many items in the list can be selected at a time. A ListBox control can provide single or
multiple selections using the SelectionMode property . If you change the selection mode property to multiple select , then you will retrieve
a collection of items from ListBox1.SelectedItems property.
listBox1.SelectionMode = SelectionMode.MultiSimple;
The following C# program initially fill seven days in a week while in the form load event and set the selection mode property to
MultiSimple. At the Button click event it will display the selected items.

using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("Sunday");
listBox1.Items.Add("Monday");
listBox1.Items.Add("Tuesday");
listBox1.Items.Add("Wednesday");
listBox1.Items.Add("Thursday");
listBox1.Items.Add("Friday");
listBox1.Items.Add("Saturday");
listBox1.SelectionMode = SelectionMode.MultiSimple;
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Object obj in listBox1.SelectedItems )
{
MessageBox.Show(obj.ToString ());
}
}
}
}
How to bind a ListBox to a List ?
First you should create a fresh List Object and add items to the List.

List<string> nList = new List<string>();


nList.Add("January");
nList.Add("February");
nList.Add("March");
nList.Add("April");
The next step is to bind this List to the Listbox. In order to do that you should set datasource of the Listbox.
listBox1.DataSource = nList;

Full Source code

private void button1_Click(object sender, EventArgs e)


{
List<string> nList = new List<string>();
nList.Add("January");
nList.Add("February");
nList.Add("March");
nList.Add("April");
listBox1.DataSource = nList;
}

How to bind a listbox to database values ?


First you should create a connection string and fetch data from database to a Dataset.

connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword";


sql = "select au_id,au_lname from authors";
After that you should set Listbox datasoure as Dataset.

listBox1.DataSource = ds.Tables[0];
listBox1.ValueMember = "au_id";
listBox1.DisplayMember = "au_lname";
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
//connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword";
//sql = "select au_id,au_lname from authors";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
listBox1.DataSource = ds.Tables[0];
listBox1.ValueMember = "au_id";
listBox1.DisplayMember = "au_lname";
}
catch (Exception ex)
{
MessageBox.Show("Cannot open connection ! ");
}
}
}
}
How to refresh DataSource of a ListBox ?
How to clear the Listbox if its already binded with datasource ?
When you want to clear the Listbox, if the ListBox already binded with Datasource, you have to set the Datasource of Listbox as null.
listBox1.DataSource = null;
How to SelectedIndexChanged event in ListBox ?
This event is fired when the item selection is changed in a ListBox. You can use this event in a situation that you want select an item from
your listbox and accodring to this selection you can perform other programming needs.
You can add the event handler using the Properties Window and selecting the Event icon and double-clicking on SelectedIndexChanged
as you can see in following image.

The event will fire again when you select a new item. You can write your code within SelectedIndexChanged event . When you double
click on ListBox the code will automatically come in you code editor like the following image.

From the following example you can understand how to fire the SelectedIndexChanged event

First you should drag two listboxes on your Form. First listbox you should set the List as Datasource, the List contents follows:

List<string> nList = new List<string>();


nList.Add("First Quarter");
nList.Add("Second Quarter");
When you load this form you can see the listbox is populated with List and displayed first quarter and second quarter. When you click the
"Fist Quarter" the next listbox is populated with first quarter months and when you click "Second Quarter" you can see the second listbox
is changed to second quarter months. From the following program you can understand how this happened.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Collections.Generic;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

List < string > fQ = new List < string > ();
List < string > sQ = new List < string > ();

private void Form1_Load(object sender, EventArgs e)


{
fQ.Add("January");
fQ.Add("February");
fQ.Add("March");

sQ.Add("April");
sQ.Add("May");
sQ.Add("June");

List < string > nList = new List < string > ();

nList.Add("First Quarter");
nList.Add("Second Quarter");

listBox1.DataSource = nList;
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
if (listBox1.SelectedIndex == 0)
{
listBox2.DataSource = null;
listBox2.DataSource = fQ;
}
else if (listBox1.SelectedIndex == 1)
{
listBox2.DataSource = null;
listBox2.DataSource = sQ;
}
}

}
}

C# Checked ListBox Control

The CheckedListBox control gives you all the capability of a list box and also allows you to display a check mark next to the items in the
list box.
The user can place a check mark by one or more items and the checked items can be navigated with the
CheckedListBox.CheckedItemCollection and CheckedListBox.CheckedIndexCollection. To add objects to the list at run time, assign an
array of object references with the AddRange method. The list then displays the default string value for each object.
Dim days As String() = {"Sunday", "Monday", "Tuesday"};
checkedListBox1.Items.AddRange(days);
You can add individual items to the list with the Add method. The CheckedListBox object supports three states through the CheckState
enumeration: Checked, Indeterminate, and Unchecked.
checkedListBox1.Items.Add("Sunday", CheckState.Checked);
checkedListBox1.Items.Add("Monday", CheckState.Unchecked);
checkedListBox1.Items.Add("Tuesday", CheckState.Indeterminate);

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
checkedListBox1.Items.Add("Sunday", CheckState.Checked);
checkedListBox1.Items.Add("Monday", CheckState.Unchecked);
checkedListBox1.Items.Add("Tuesday", CheckState.Indeterminate);
checkedListBox1.Items.Add("Wednesday", CheckState.Checked);
checkedListBox1.Items.Add("Thursday", CheckState.Unchecked);
checkedListBox1.Items.Add("Friday", CheckState.Indeterminate);
checkedListBox1.Items.Add("Saturday", CheckState.Indeterminate);
}
}
}

C# RadioButton Control

A radio button or option button enables the user to select a single option from a group of choices when paired with other RadioButton
controls. When a user clicks on a radio button, it becomes checked, and all other radio buttons with same group become unchecked
The RadioButton control can display text, an Image, or both. Use the Checked property to get or set the state of a RadioButton.
radioButton1.Checked = true;
The radio button and the check box are used for different functions. Use a radio button when you want the user to choose only one option.
When you want the user to choose all appropriate options, use a check box. Like check boxes, radio buttons support a Checked property
that indicates whether the radio button is selected.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
radioButton1.Checked = true;
}

private void button1_Click(object sender, EventArgs e)


{
if (radioButton1.Checked == true)
{
MessageBox.Show ("You are selected Red !! ");
return;
}
else if (radioButton2.Checked == true)
{
MessageBox.Show("You are selected Blue !! ");
return;
}
else
{
MessageBox.Show("You are selected Green !! ");
return;
}
}
}
}

C# CheckBox Control

CheckBoxes allow the user to make multiple selections from a number of options. CheckBox to give the user an option, such as true/false
or yes/no. You can click a check box to select it and click it again to deselect it.
The CheckBox control can display an image or text or both. Usually CheckBox comes with a caption, which you can set in the Text
property.
checkBox1.Text = "Net-informations.com";
You can use the CheckBox control ThreeState property to direct the control to return the Checked, Unchecked, and Indeterminate values.
You need to set the check boxs ThreeState property to True to indicate that you want it to support three states.
checkBox1.ThreeState = true;
The radio button and the check box are used for different functions. Use a radio button when you want the user to choose only one
option.When you want the user to choose all appropriate options, use a check box. The following C# program shows how to find a
checkbox is selected or not.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string msg = "";

if (checkBox1.Checked == true)
{
msg = "net-informations.com";
}

if (checkBox2.Checked == true)
{
msg = msg + " vb.net-informations.com";
}

if (checkBox3.Checked == true)
{
msg = msg + " csharp.net-informations.com";
}

if (msg.Length > 0)
{
MessageBox.Show (msg + " selected ");
}
else
{
MessageBox.Show ("No checkbox selected");
}

checkBox1.ThreeState = true;
}
}
}

C# PictureBox Control

The Windows Forms PictureBox control is used to display images in bitmap, GIF , icon , or JPEG formats.

You can set the Image property to the Image you want to display, either at design time or at run time. You can programmatically change
the image displayed in a picture box, which is particularly useful when you use a single form to display different pieces of information.
pictureBox1.Image = Image.FromFile("c:\\testImage.jpg");
The SizeMode property, which is set to values in the PictureBoxSizeMode enumeration, controls the clipping and positioning of the image
in the display area.
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
There are five different PictureBoxSizeMode is available to PictureBox control.
AutoSize - Sizes the picture box to the image.
CenterImage - Centers the image in the picture box.
Normal - Places the upper-left corner of the image at upper
left in the picture box
StretchImage - Allows you to stretch the image in code
The PictureBox is not a selectable control, which means that it cannot receive input focus. The following C# program shows how to load a
picture from a file and display it in streach mode.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
pictureBox1.Image = Image.FromFile("c:\\testImage.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}

}
}

C# ProgressBar Control

A progress bar is a control that an application can use to indicate the progress of a lengthy operation such as calculating a complex result,
downloading a large file from the Web etc.

ProgressBar controls are used whenever an operation takes more than a short period of time. The Maximum and Minimum properties
define the range of values to represent the progress of a task.
Minimum : Sets the lower value for the range of valid values for progress.
Maximum : Sets the upper value for the range of valid values for progress.
Value : This property obtains or sets the current level of progress.
By default, Minimum and Maximum are set to 0 and 100. As the task proceeds, the ProgressBar fills in from the left to the right. To delay
the program briefly so that you can view changes in the progress bar clearly.
The following C# program shows a simple operation in a progressbar .

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i;

progressBar1.Minimum = 0;
progressBar1.Maximum = 200;

for (i = 0; i <= 200; i++)


{
progressBar1.Value = i;
}

}
}

C# ScrollBars Control

A ScrollBar allows you to view content that is outside of the current viewing area by sliding the Thumb to make the content visible.

The ScrollBar control contains a Track control. The Track control consists of a Thumb control and two RepeatButton controls. You can
increase and decrease the Value property of the ScrollBar control by pressing the RepeatButton controls or by moving the Thumb. You
can set the Value property yourself in code, which moves the scroll box to match. The Minimum and Maximum properties determine the
range of values that the control can display. The default range of values for the Value property is from 0 to 1.
The following C# program shows a TextBox control with scrollbars.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
textBox1.Multiline = true;
textBox1.ScrollBars = ScrollBars.Both;
}
}
}

C# DateTimePicker Control

The DateTimePicker control allows you to display and collect date and time from the user with a specified format.

The DateTimePicker control has two parts, a label that displays the selected date and a popup calendar that allows users to select a new
date. The most important property of the DateTimePicker is the Value property, which holds the selected date and time.
dateTimePicker1.Value = DateTime.Today;
The Value property contains the current date and time the control is set to. You can use the Text property or the appropriate member of
Value to get the date and time value.
DateTime iDate;
iDate = dateTimePicker1.Value;
The control can display one of several styles, depending on its property values. The values can be displayed in four formats, which are set
by the Format property: Long, Short, Time, or Custom.
dateTimePicker1.Format = DateTimePickerFormat.Short;
The following C# program shows how to set and get the value of a DateTimePicker1 control.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
dateTimePicker1.Format = DateTimePickerFormat.Short;
dateTimePicker1.Value = DateTime.Today;
}

private void button1_Click(object sender, EventArgs e)


{
DateTime iDate;
iDate = dateTimePicker1.Value;
MessageBox.Show("Selected date is " + iDate);
}
}
}

C# Treeview Control

The TreeView control contains a hierarchy of TreeViewItem controls. It provides a way to display information in a hierarchical structure
by using collapsible nodes . The top level in a tree view are root nodes that can be expanded or collapsed if the nodes have child nodes.

You can explicitly define the TreeView content or a data source can provide the content. The user can expand the TreeNode by clicking
the plus sign (+) button, if one is displayed next to the TreeNode, or you can expand the TreeNode by calling the TreeNode.Expand
method. You can also navigate through tree views with various properties: FirstNode, LastNode, NextNode, PrevNode, NextVisibleNode,
PrevVisibleNode.
The fullpath method of treeview control provides the path from root node to the selected node.
treeView1.SelectedNode.FullPath.ToString ();
Tree nodes can optionally display check boxes. To display the check boxes, set the CheckBoxes property of the TreeView to true.
treeView1.CheckBoxes = true;
The following C# program shows a simple demonstration of treeview control

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
TreeNode tNode ;
tNode = treeView1.Nodes.Add("Websites");

treeView1.Nodes[0].Nodes.Add("Net-informations.com");
treeView1.Nodes[0].Nodes[0].Nodes.Add("CLR");

treeView1.Nodes[0].Nodes.Add("Vb.net-informations.com");
treeView1.Nodes[0].Nodes[1].Nodes.Add("String Tutorial");
treeView1.Nodes[0].Nodes[1].Nodes.Add("Excel Tutorial");

treeView1.Nodes[0].Nodes.Add("Csharp.net-informations.com");
treeView1.Nodes[0].Nodes[2].Nodes.Add("ADO.NET");
treeView1.Nodes[0].Nodes[2].Nodes[0].Nodes.Add("Dataset");
}

private void button1_Click(object sender, EventArgs e)


{
MessageBox.Show(treeView1.SelectedNode.FullPath.ToString ());
}
}
}

C# ListView Control

The ListView control is an ItemsControl that is derived from ListBox.

ListView provides a large number of properties that provide flexibility in appearance and behavior. The View property allows you to
change the way in which items are displayed. The SelectionMode property for a ListView determines how many items a user can select at
one time.
The following C# program first set its view property as Details and GridLines property as true and FullRowSelect as true.
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
After that it fills column header and then the column values.
listView1.Columns.Add("ProductName", 100);
Finally in the button click event, it will display the selected row values in a message box.

using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;

//Add column header


listView1.Columns.Add("ProductName", 100);
listView1.Columns.Add("Price", 70);
listView1.Columns.Add("Quantity", 70);

//Add items in the listview


string[] arr = new string[4];
ListViewItem itm ;

//Add first item


arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);

//Add second item


arr[0] = "product_2";
arr[1] = "200";
arr[2] = "20";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
}

private void button1_Click(object sender, EventArgs e)


{
string productName = null;
string price = null;
string quantity = null;

productName = listView1.SelectedItems[0].SubItems[0].Text;
price = listView1.SelectedItems[0].SubItems[1].Text;
quantity = listView1.SelectedItems[0].SubItems[2].Text;

MessageBox.Show (productName + " , " + price + " , " + quantity);


}
}
}

C# Menu Control

A Menu on a Windows Form is created with a MainMenu object, which is a collection of MenuItem objects. MainMenu is the container
for the Menu structure of the form and menus are made of MenuItem objects that represent individual parts of a menu.
You can add menus to Windows Forms at design time by adding the MainMenu component and then appending menu items to it using the
Menu Designer.

After drag the Menustrip on your form you can directly create the menu items by type a value into the "Type Here" box on the menubar
part of your form. From the following picture you can understand how to create each menu items on mainmenu Object.

If you need a seperator bar , right click on your menu then go to insert->Seperator.
After creating the Menu on the form , you have to double click on each menu item and write the programs there depends on your
requirements. The following C# program shows how to show a messagebox when clicking a Menu item.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("You are selected MenuItem_1");
}
}
}

C# MDI Form

A Multiple Document Interface (MDI) programs can display multiple child windows inside them. This is in contrast to single document
interface (SDI) applications, which can manipulate only one document at a time. Visual Studio Environment is an example of Multiple
Document Interface (MDI) and notepad is an example of an SDI application. MDI applications often have a Window menu item with
submenus for switching between windows or documents.
Any windows can become an MDI parent, if you set the IsMdiContainer property to True.
IsMdiContainer = true;
The following C# program shows a MDI form with two child forms. Create a new C# project, then you will get a default form Form1 .
Then add two mnore forms in the project (Form2 , Form 3) . Create a Menu on your form and call these two forms on menu click event.
Click here to see how to create a Menu on your form How to Menu Control C#.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
IsMdiContainer = true;
}

private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)


{
Form2 frm2 = new Form2();
frm2.Show();
frm2.MdiParent = this;
}

private void menu2ToolStripMenuItem_Click(object sender, EventArgs e)


{
Form3 frm3 = new Form3();
frm3.Show();
frm3.MdiParent = this;
}
}
}

C# Color Dialog Box

There are several classes that implement common dialog boxes, such as color selection , print setup etc.

A ColorDialog object is a dialog box with a list of colors that are defined for the display system. The user can select or create a particular
color from the list, which is then reported back to the application when the dialog box exits. You can invite a color dialog box by calling
ShowDialog() method.
ColorDialog dlg = new ColorDialog();
dlg.ShowDialog();
The following C# program invites a color dialog box and retrieve the selected color to a string.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
ColorDialog dlg = new ColorDialog();
dlg.ShowDialog();

if (dlg.ShowDialog() == DialogResult.OK)
{
string str = null;
str = dlg.Color.Name;
MessageBox.Show (str);
}
}
}
}

C# Font Dialog Box

Font dialog box represents a common dialog box that displays a list of fonts that are currently installed on the system. The Font dialog box
lets the user choose attributes for a logical font, such as font family and associated font style, point size, effects , and a script .

The following C# program invites a Font Dialog Box and retrieve the selected Font Name and Font Size.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
FontDialog dlg = new FontDialog();
dlg.ShowDialog();

if (dlg.ShowDialog() == DialogResult.OK)
{
string fontName;
float fontSize;
fontName = dlg.Font.Name;
fontSize = dlg.Font.Size;
MessageBox.Show(fontName + " " + fontSize );
}
}
}
}

C# OpenFile Dialog Box


The OpenFileDialog component allows users to browse the folders of their computer or any computer on the network and select one or
more files to open. The dialog box returns the path and name of the file the user selected in the dialog box.

The FileName property can be set prior to showing the dialog box. This causes the dialog box to initially display the given filename. In
most cases, your applications should set the InitialDirectory, Filter, and FilterIndex properties prior to calling ShowDialog.
The following C# program invites an OpenFile Dialog Box and retrieve the selected filename to a string.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
OpenFileDialog dlg = new OpenFileDialog();
dlg.ShowDialog();

if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName;
fileName = dlg.FileName;
MessageBox.Show(fileName);
}
}
}
}

C# Print Dialog Box


A user can use the Print dialog box to select a printer, configure it, and perform a print job. Print dialog boxes provide an easy way to
implement Print and Print Setup dialog boxes in a manner consistent with Windows standards.

The Print dialog box includes a Print Range group of radio buttons that indicate whether the user wants to print all pages, a range of pages,
or only the selected text. The dialog box includes an edit control in which the user can type the number of copies to print. By default, the
Print dialog box initially displays information about the current default printer.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Win
dowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
PrintDialog dlg = new PrintDialog();
dlg.ShowDialog();
}
}
}

keyPress event in C#

Handle Keyboard Input at the Form Level in C#


Windows Forms processes keyboard input by raising keyboard events in response to Windows messages. Most Windows Forms
applications process keyboard input exclusively by handling the keyboard events.
How do I detect keys pressed in C#
You can detect most physical key presses by handling the KeyDown or KeyUp events. Key events occur in the following order:
KeyDown
KeyPress
KeyUp
How to detect when the Enter Key Pressed in C#
The following C# code behind creates the KeyDown event handler. If the key that is pressed is the Enter key, a MessegeBox will
displayed .
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter Key Pressed ");
}
How to get TextBox1_KeyDown event in your C# source file ?
Select your TextBox control on your Form and goto Properties window. Select Event icon on the properties window and scroll down and
find the KeyDown event from the list and double click the Keydown Event. The you will get the KeyDown event in your source code
editor.
private void textBox1_KeyDown(.....)
{
}

The following C# source code shows how to capture Enter KeyDown event from a TextBox Control.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)


{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enwter Key Pressed ");
}
}
}
}

How to create Dynamic Controls in C# ?

How to create Control Arrays in C# ?


Visual Studio .NET does not have control arrays like Visual Basic 6.0 does. The good news is that you can still set things up to do similar
things. The advantages of C# dynamic controls is that they can be created in response to how the user interacts with the application.
Common controls that are added during run-time are the Button and TextBox controls. But of course, nearly every C# control can be
created dynamically.
How to create Dynamic Controls in C# ?
The following program shows how to create a dynamic TextBox control in C# and setting the properties dynamically for each TextBox
control. Drag a Button control in the form and copy and paste the following source code . Here each Button click the program create a
new TextBox control dyanmically.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int cLeft = 1;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
AddNewTextBox();
}

public System.Windows.Forms.TextBox AddNewTextBox()


{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
this.Controls.Add(txt);
txt.Top = cLeft * 25;
txt.Left = 100;
txt.Text = "TextBox " + this.cLeft.ToString();
cLeft = cLeft + 1;
return txt;
}
}
}

Keep Form on Top of All Other Windows

The System.Windows.Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user
interface features available in the Microsoft Windows operating system. You can bring a Form on top of application by simply setting the
Form.topmost form property to true will force the form to the top layer of the screen, while leaving the user able to enter data in the forms
below.
Form2 frm = new Form2();
frm.TopMost = true;
frm.Show();
Topmost forms are always displayed at the highest point in the z-order of the windows on the desktop. You can use this property to create
a form that is always displayed in your application, such as a MessageBox window.
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Form2 frm = new Form2();
frm.TopMost = true;
frm.Show();
}
}
}

You might also like