Tuesday 28 January 2014

C# Programming.


C# Hello World Example

A C# program basically consists of the following parts:

  • Namespace declaration
  • A class
  • Class methods
  • Class attributes
  • A Main method
  • Statements & Expressions
  • Comments

Let us look at a simple code that would print the words "Hello World":

using System;
namespace HelloWorldApplication
{
   class HelloWorld
   {
      static void Main(string[] args)
      {
         /* my first program in C# */
         Console.WriteLine("Hello World");
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following result:

Hello World

Let us look at various parts of the above program:

  • The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements.
  • The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld.
  • The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally would contain more than one method. Methods define the behavior of the class. However, the HelloWorld class has only one method Main.
  • The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class will do when executed
  • The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program.
  • The Main method specifies its behavior with the statement Console.WriteLine("Hello World");

WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.

  • The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET.

It's worth to note the following points:

  • C# is case sensitive.
  • All statements and expression must end with a semicolon (;).
  • The program execution starts at the Main method.
  • Unlike Java, file name could be different from the class name.

 

Encapsulation is implemented by using Access specifiers.

An Access specifier defines the scope and visibility of a class member.

C# supports the following access specifiers:

  • Public
  • Private
  • Protected
  • Internal
  • Protected internal

 

Public Access Specifier


Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.


Private Access Specifier


Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.


Protected Access Specifier


Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. We will discuss this in more details in the inheritance chapter.

 

 

 

 

 

 

C# - Exception Handling



An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally and throw.

  • TRY: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
  • CATCH: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
  • FINALLY: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
  • THROW: A program throws an exception when a problem shows up. This is done using a throw keyword.

Syntax


Assuming a block will raise and exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception.

Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
   // statements causing exception
}
catch( ExceptionName e1 )
{
   // error handling code
}
catch( ExceptionName e2 )
{
   // error handling code
}
catch( ExceptionName eN )
{
   // error handling code
}
finally
{
   // statements to be executed

 

Thursday 2 January 2014

Cascading Dropdown List for Country/State/City in ASP.Net using Entity Framework

Cascading Dropdown List for Country/State/City in ASP.Net using Entity Framework

In this blog I am going to show how we can work with cascading dropdown list for country/state/city in asp.net using Entity Framework.

Create three tables as per our need:
 
CREATE TABLE country
  (
     countryID     INT NOT NULL,
     countryName   varchar(50) NOT NULL,
     PRIMARY KEY (countryID ),
  );
CREATE TABLE state
  (
 stateID     INT NOT NULL,
 countryID INT NOTNULL,
 stateName   varchar(50) NOT NULL,
 PRIMARY KEY (stateID ),
 FOREIGN KEY (countryID ) REFERENCES country (countryID));

CREATE TABLE city
  (
cityID     INT NOT NULL,
 stateID INT NOTNULL,
 cityName   varchar(50) NOT NULL,
 PRIMARY KEY (cityID),
 FOREIGN KEY (stateID) REFERENCES state (stateID));

First create an empty web application




Add model as per we did in earlier for entity framework do the necessary






Add a web page to the solution and copy paste this in .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="cascading.aspx.cs" Inherits="counrtybasedropdown.cascading" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <center>
            <h3>
                Cascading DropDownList for Country/State/City in ASP.Net</h3>
            <table>
                <tr>
                    <td>
                        Select a Country :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select a State :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlState" runat="server" Enabled="false" AutoPostBack="true"
                            OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
                       < /asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select a City :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCity" runat="server" Enabled="false">
                        </asp:DropDownList>
                    </td>
                </tr>
            </table>
        </center>
    </div>
    </form>
</body>
</html>
Your .aspx.cs should be as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace counrtybasedropdown
{
    public partial class cascading : System.Web.UI.Page
    {
        Database1Entities dbEntity = new Database1Entities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var country = from c in dbEntity.countries select new { c.countryID, c.countryName };
                ddlCountry.DataSource = country.ToList();
                ddlCountry.DataValueField = "countryID";
                ddlCountry.DataTextField = "countryName";
                ddlCountry.DataBind();
                ddlCountry.Items.Insert(0, "--Select--");
            }
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            int countyID = Convert.ToInt16(ddlCountry.SelectedValue.ToString());
            var state = from s in dbEntity.states where s.countryID.Equals(countyID) select new { s.stateID, s.stateName };
            ddlState.DataSource = state.ToList();
            ddlState.Enabled = true;
            ddlState.DataValueField = "stateID";
            ddlState.DataTextField = "stateName";
            ddlState.DataBind();
            ddlState.Items.Insert(0, "--Select--");
        }

        protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
        {
            int stateID = Convert.ToInt16(ddlState.SelectedValue.ToString());
            var city = from c in dbEntity.cities where c.stateID.Equals(stateID) select new { c.cityID, c.cityName };
            ddlCity.DataSource = city.ToList();
            ddlCity.Enabled = true;
            ddlCity.DataValueField = "cityID";
            ddlCity.DataTextField = "cityName";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, "--Select--");
        }
    }
}

Happy coding..

Cascading (Country,City)drop down list in asp.net


Developing a registration form with Country and city name .
I need the city to be loaded in the dropdown list based on the selection in country dropdownlist.


CODE:


   public void Bind_ddlCountry()
   {
       SqlConObject.Open();
       SqlCommand cmd = new SqlCommand("sp_Country", SqlConObject);
       cmd.CommandType = CommandType.StoredProcedure;

       SqlDataReader dr = cmd.ExecuteReader();
       ddlCountry.DataSource = dr;
       ddlCountry.Items.Clear();
       ddlCountry.Items.Add("Select");
       ddlCountry.DataTextField = "Country_Name";
       ddlCountry.DataValueField = "Country_ID";
       ddlCountry.DataBind();
       SqlConObject.Close();
   }


   public void Bind_ddlCity(int countryid)
   {
       SqlConObject.Open();
       SqlCommand cmd = new SqlCommand("sp_City", SqlConObject);
       cmd.CommandType = CommandType.StoredProcedure;
       cmd.Parameters.Add("@Countryid", SqlDbType.Int).Value = countryid;
       SqlDataReader dr = cmd.ExecuteReader();
       ddlCity.DataSource = dr;
       ddlCity.Items.Clear();
       ddlCity.Items.Add("Select");
       ddlCity.DataTextField = "City_Name";
       ddlCity.DataValueField = "Country_ID";
       ddlCity.DataBind();
       SqlConObject.Close();
      
   }
}
  protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        Bind_ddlCity(int.Parse(ddlCountry.SelectedValue));
    }

 

Populate Cascading DropDownList On Selection ASP.NET

Populate Cascading DropDownList On Selection ASP.NET
Populate Cascading DropDownList In Asp.Net C# VB.NET Based On Selection Of Other DropDown In SelectedIndexChanged Event. binding state DropDown based on selection of Country DropDownlist and then populating Cities on selection of State.

There are several situations where we need to populate second or third dropdownlist list based on selection of first or second dropdwonlist in asp.net.

populate dropdown based on selection in SelectedIndexChanged Event asp.net
For this we need to write code in code behind in the SelectedIndexChanged Event of respective Dropdownlist to implement the cascading of DropDowns.

HTML SOURCE OF PAGE
 
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <table><tr>
   4:  <td><strong>Country :</strong></td>
   5:  <td><asp:DropDownList ID="ddlCountry" runat="server"
   6:                        AutoPostBack="True" 
   7:                        onselectedindexchanged=
   8:                   "ddlCountry_SelectedIndexChanged">
   9:      </asp:DropDownList>
  10:  </td>
  11:   
  12:  <td><strong>State:</strong></td>
  13:  <td><asp:DropDownList ID="ddlState" runat="server" 
  14:                        AutoPostBack="True" 
  15:                        onselectedindexchanged=
  16:                   "ddlState_SelectedIndexChanged">
  17:      </asp:DropDownList></td>
  18:   
  19:  <td><strong>City:</strong></td>
  20:  <td><asp:DropDownList ID="ddlCity" runat="server" 
  21:                        AutoPostBack="True">
  22:      </asp:DropDownList></td>
  23:  </tr>
  24:  <tr><td><asp:Label ID="lblMsg" runat="server">
  25:         </asp:Label>
  26:      </td>
  27:  </tr>  
  28:  </table>
  29:   </div>
  30:   </form>

Write following code in respective events of page and dropdownlists.

C# CODE
001protected void Page_Load(object sender, EventArgs e)
002    {
003        if (!IsPostBack)
004        {
005            FillCountry();
006        }
007    }
008    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
009    {
010        int CountryID = Convert.ToInt32(ddlCountry.SelectedValue.ToString());
011        FillStates(CountryID);
012        ddlCity.SelectedIndex = 0;
013    }
014    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
015    {
016        int StateID = Convert.ToInt32(ddlState.SelectedValue.ToString());
017        FillCities(StateID);
018    }
019 
020    private void FillCountry()
021    {
022        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
023        SqlConnection con = new SqlConnection(strConn);
024        SqlCommand cmd = new SqlCommand();
025        cmd.Connection = con;
026        cmd.CommandType = CommandType.Text;
027        cmd.CommandText = "SELECT CountryID, CountryName FROM Country";
028        DataSet objDs = new DataSet();
029        SqlDataAdapter dAdapter = new SqlDataAdapter();
030        dAdapter.SelectCommand = cmd;
031        con.Open();
032        dAdapter.Fill(objDs);
033        con.Close();
034        if (objDs.Tables[0].Rows.Count > 0)
035        {
036            ddlCountry.DataSource = objDs.Tables[0];
037            ddlCountry.DataTextField = "CountryName";
038            ddlCountry.DataValueField = "CountryID";
039            ddlCountry.DataBind();
040            ddlCountry.Items.Insert(0, "--Select--");
041        }
042        else
043        {
044            lblMsg.Text = "No Countries found";
045        }
046    }
047 
048    private void FillStates(int countryID)
049    {
050        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
051        SqlConnection con = new SqlConnection(strConn);
052        SqlCommand cmd = new SqlCommand();
053        cmd.Connection = con;
054        cmd.CommandType = CommandType.Text;
055        cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID";
056        cmd.Parameters.AddWithValue("@CountryID", countryID);
057        DataSet objDs = new DataSet();
058        SqlDataAdapter dAdapter = new SqlDataAdapter();
059        dAdapter.SelectCommand = cmd;
060        con.Open();
061        dAdapter.Fill(objDs);
062        con.Close();
063        if (objDs.Tables[0].Rows.Count > 0)
064        {
065            ddlState.DataSource = objDs.Tables[0];
066            ddlState.DataTextField = "StateName";
067            ddlState.DataValueField = "StateID";
068            ddlState.DataBind();
069            ddlState.Items.Insert(0, "--Select--");
070        }
071        else
072        {
073            lblMsg.Text = "No states found";
074        }
075    }
076 
077    private void FillCities(int stateID)
078    {
079        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
080        SqlConnection con = new SqlConnection(strConn);
081        SqlCommand cmd = new SqlCommand();
082        cmd.Connection = con;
083        cmd.CommandType = CommandType.Text;
084        cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID";
085        cmd.Parameters.AddWithValue("@StateID", stateID);
086        DataSet objDs = new DataSet();
087        SqlDataAdapter dAdapter = new SqlDataAdapter();
088        dAdapter.SelectCommand = cmd;
089        con.Open();
090        dAdapter.Fill(objDs);
091        con.Close();
092        if (objDs.Tables[0].Rows.Count > 0)
093        {
094            ddlCity.DataSource = objDs.Tables[0];
095            ddlCity.DataTextField = "CityName";
096            ddlCity.DataValueField = "CItyID";
097            ddlCity.DataBind();
098            ddlCity.Items.Insert(0, "--Select--");
099        }
100        else
101        {
102            lblMsg.Text = "No Cities found";
103        }
104    }

VB.NET
01Protected Sub Page_Load(sender As Object, e As EventArgs)
02 If Not IsPostBack Then
03  FillCountry()
04 End If
05End Sub
06Protected Sub ddlCountry_SelectedIndexChanged(sender As Object, e As EventArgs)
07 Dim CountryID As Integer = Convert.ToInt32(ddlCountry.SelectedValue.ToString())
08 FillStates(CountryID)
09 ddlCity.SelectedIndex = 0
10End Sub
11Protected Sub ddlState_SelectedIndexChanged(sender As Object, e As EventArgs)
12 Dim StateID As Integer = Convert.ToInt32(ddlState.SelectedValue.ToString())
13 FillCities(StateID)
14End Sub
15 
16Private Sub FillCountry()
17 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
18 Dim con As New SqlConnection(strConn)
19 Dim cmd As New SqlCommand()
20 cmd.Connection = con
21 cmd.CommandType = CommandType.Text
22 cmd.CommandText = "SELECT CountryID, CountryName FROM Country"
23 Dim objDs As New DataSet()
24 Dim dAdapter As New SqlDataAdapter()
25 dAdapter.SelectCommand = cmd
26 con.Open()
27 dAdapter.Fill(objDs)
28 con.Close()
29 If objDs.Tables(0).Rows.Count > 0 Then
30  ddlCountry.DataSource = objDs.Tables(0)
31  ddlCountry.DataTextField = "CountryName"
32  ddlCountry.DataValueField = "CountryID"
33  ddlCountry.DataBind()
34  ddlCountry.Items.Insert(0, "--Select--")
35 Else
36  lblMsg.Text = "No Countries found"
37 End If
38End Sub
39 
40Private Sub FillStates(countryID As Integer)
41 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
42 Dim con As New SqlConnection(strConn)
43 Dim cmd As New SqlCommand()
44 cmd.Connection = con
45 cmd.CommandType = CommandType.Text
46 cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"
47 cmd.Parameters.AddWithValue("@CountryID", countryID)
48 Dim objDs As New DataSet()
49 Dim dAdapter As New SqlDataAdapter()
50 dAdapter.SelectCommand = cmd
51 con.Open()
52 dAdapter.Fill(objDs)
53 con.Close()
54 If objDs.Tables(0).Rows.Count > 0 Then
55  ddlState.DataSource = objDs.Tables(0)
56  ddlState.DataTextField = "StateName"
57  ddlState.DataValueField = "StateID"
58  ddlState.DataBind()
59  ddlState.Items.Insert(0, "--Select--")
60 Else
61  lblMsg.Text = "No states found"
62 End If
63End Sub
64 
65Private Sub FillCities(stateID As Integer)
66 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
67 Dim con As New SqlConnection(strConn)
68 Dim cmd As New SqlCommand()
69 cmd.Connection = con
70 cmd.CommandType = CommandType.Text
71 cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"
72 cmd.Parameters.AddWithValue("@StateID", stateID)
73 Dim objDs As New DataSet()
74 Dim dAdapter As New SqlDataAdapter()
75 dAdapter.SelectCommand = cmd
76 con.Open()
77 dAdapter.Fill(objDs)
78 con.Close()
79 If objDs.Tables(0).Rows.Count > 0 Then
80  ddlCity.DataSource = objDs.Tables(0)
81  ddlCity.DataTextField = "CityName"
82  ddlCity.DataValueField = "CItyID"
83  ddlCity.DataBind()
84  ddlCity.Items.Insert(0, "--Select--")
85 Else
86  lblMsg.Text = "No Cities found"
87 End If
88End Sub

Build and run the code.