Wednesday, 4 June 2014

C# Tutorial-Basics-Variables

A variable is a place to store data. 
A variable has a name and a data type.
A data type determines, what values can be assigned to the variable. Integers, strings, boolean values etc. 
Over the time of the program, variables can obtain various values of the same data type. Variables are always initialized to the default value of their type before any reference to the variable can be made.

using System;

public class CSharpApp
{
    static void Main()
    {
        string city = "Chennai";
        string name = "Modi"; int age = 55;
        string nationality = "Indian";

        Console.WriteLine(city);
        Console.WriteLine(name);
        Console.WriteLine(age);
        Console.WriteLine(nationality);

        city = "Delhi";
        Console.WriteLine(city);
    }
}

In the above example, we work with four variables.

string city = "Chennai";
We declare a city variable of the string type and initialize it to the "Chennai" value.

string name = "Modi"; int age = 55;
We declare and initialize two more variables. We can put two statements into one line. But for readability reasons, each statement should be on a separate line.

Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);
We print the values of the variables to the terminal.

city = "Delhi";
We assign a new value to the city variable.
$ ./variables.exe 
Chennai
Modi
55
Indian
Delhi
This is the output of the example.

C# Tutorial-Basics-Command Line Arguments

C# programs can receive command line arguments. They follow the name of the program, when we run it.

using System;

public class CSharpApp 
{
    static void Main(string[] args) 
    {
        for (int i=0; i<args.Length; i++) 
        {
            Console.WriteLine("{0}", args[i]);
        }
    }
}

Command line arguments can be passed to the Main() method.

public static void Main(string[] args) 

This Main() method receives a string array of command line arguments.
for (int i=0; i<args.Length; i++) 
{
    Console.WriteLine("{0}", args[i]);
}

We go through the array of these arguments with a for loop and print them to the console. TheLength property gives the number of elements in the array. Loops and arrays will be described in more detail later.
$ ./commandargs.exe 1 2 3
1
2
3
We provide three numbers as command line arguments and these are printed to the console.

C# Tutorial-Basics-Reading Values

We can use the Console class to read values.

using System;

public class ReadLine
{
    static void Main()
    {
        string name;

        Console.Write("Enter your name: ");
        name = Console.ReadLine();
        Console.WriteLine("Hello {0}", name);
    }
}

The second program will read a value from a console and print it.

string name;
We declare a variable. The variable is called 'name'. 
Unlike constants, which store only one value during the life of the program, variables may store various different values of the same type. 
Thestring keyword defines the data type of the variable. Our variable will hold string values.

name = Console.ReadLine();
We read a line from the terminal. When we hit the Enter key, the input is assigned to the name variable.

Console.WriteLine("Hello {0}", name);
In this code line, we perform variable interpolation. 
Variable interpolation is replacing variables with their values inside string literals. Another names for variable interpolation are: variable substitution and variable expansion.
$ ./readline.exe 
Enter your name: Steve Jobs
Hello Steve Jobs
This is the output of the program.

C# Tutorial-Basics-simple program

In this part of the C# tutorial, we will cover basic programming concepts of the C# language. 
We will work with variables, constants and basic data types. We will read and write to the console; we will mention variable interpolation.
We start with a very simple code example.

using System;

public class Simple
{
    static void Main()
    {
        Console.WriteLine("This is C#");
    }
}

This is our first C# program. It will print "This is C#" message to the console. 

We will explain it line by line.
using System;
The using keyword imports a specific namespace to our program. Namespaces are created to group and/or distinguish named entities from other ones. This prevents name conflicts. This line is a C# statement. Each statement is ended with a semicolon.

public class Simple
{
    ...
}
Each C# program is structured. It consists of classes and its members.
A class is a basic building block of a C# program. 
The public keyword gives unrestricted access to this class. 
The above code is a class definition. The definition has a body, which starts with a left curly brace ({) and ends with a right curly brace (}).

static void Main()
{
    ...
}
The Main() is a method. A method is a piece of code created to do a specific job. 
Instead of putting all code into one place, we divide it into pieces, called methods. 
This brings modularity to our application.
 Each method has a body, in which we place statements. The body of a method is enclosed by curly brackets. 
The specific job for the Main() method is to start the application. It is the entry point to each console C# program. 
The method is declared to be static. This static method can be called without the need to create an instance of the CSharApp class. 
First we need start the application and after that, we are able to create instances of classes.

Console.WriteLine("This is C#");
In this code line, we print the "This is C#" string to the console. 
To print a message to the console, we use the WriteLine() method of the Console class. The class represents the standard input, output, and error streams for console applications. Note that Console class is part of the System namespace. 
This line was the reason to import the namespace with the using System; statement. 
If we didn't use the statement, we would have to use the fully qualified name of the WriteLine() method.
This would be System.Console.WriteLine("This is C#");.
$ ./simple.exe 
This is C#
Executing the program gives the above output.

Monday, 5 May 2014

how to export data from grid view to excel in asp.net using c#

To export gridview data to excel we need to write the code like as shown below

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Export Gridview Data to Excel in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnExport" runat="server" Text="Export to Excel"
onclick="btnExport_Click" />
</form>
</body>
</html>

Now in code behind add following namespaces

C# Code
using System;
using System.Data;
using System.IO;

using System.Web.UI;

After that add following code in code behind like as shown below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
dt.Rows.Add(1, "Devi", "B.E", "Chennai");
dt.Rows.Add(2, "Ramya", "MBBS", "Coimbatore");
dt.Rows.Add(3, "Rajitha", "MBA", "Hyderabad");
dt.Rows.Add(4, "Rohini", "MSC", "Chennai");
dt.Rows.Add(5, "Mahendra", "B.E", "Bangalore");
dt.Rows.Add(6, "Krissh", "B.Tech", "Chennai");
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
BindGridview();
//Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvDetails.HeaderRow.Cells.Count; i++)
{
gvDetails.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gvDetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

}

If you observe above code I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”. If we setVerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly.

Demo


Whenever we run application we will see the screen like as shown below


User ID
User Name
Education
Location
1
Devi
B.E
Chennai
2
Ramya
MBBS
Coimbatore
3
Rajitha
MBA
Hyderabad
4
Rohini
MSC
Chennai
5
Mahendra
B.E
Bangalore
6
Krissh
B.Tech
Chennai