Friday, February 12, 2016

What is constructor in C#?



Constructor is special kinds of method which is automatically call when we create the instance or object of the class. It is also responsible for the object initialization and memory allocation of class.
Constructor name and class name should be same.

Constructor don’t return any value

We cannot inherited to the constructor

Constructor always public

Example:
Class class1
{
Public class1()
}
Types of constructor
The types of Constructor are given below:
1. Default constructor
2. Parameterized constructor
3. Private constructor
4. Copy constructor
5. Static constructor



Default constructor – A constructor without any parameter is called default constructor , in default constructor every object of the class will be initialized without any value the example of the default constructor is given below :

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

namespace WindowsFormsApplication3
{
    public class Class1
    {
        public string s,s1;
        public Class1()
        {
            s = "welcome";
            s1 = "Dot Net darpan";
        }
      
       
    }
}
.cs code - 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        Class1 obj = new Class1();
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(obj.s);
            MessageBox.Show(obj.s1);
        }
    }
}


output - 





Parameterized constructor – The constructor which have at least one parameter is called parameterized constructor .The example of the parameterized is given below: 

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

namespace WindowsFormsApplication3
{
    public class Class1
    {
        public int i, j;
        public Class1(int x, int y)
        {
            i = x;
            j = y;
          
        }
      
       
    }
}
.cs code  

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

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

        Class1 obj = new Class1(10,20);
        private void button1_Click(object sender, EventArgs e)
        {
            int a = obj.i;
            int b = obj.j;
            MessageBox.Show(a.ToString());
            MessageBox.Show(b.ToString());

        }
    }
}


output :
10
20



Copy constructor – The constructor which creates an object by copy variable from other that type of constructor is called copy constructor .the main purpose of the copy constructor is to initialize new object to the value of an existing object. The syntax of the copy constructor is given below:
Public class class1
{
int I,j;
public class1(class1 o)
{
I=o.i;
J=o.j;
}
}
Class1 obj1=new obj1(10,20)
Class1 obj2=new obj2(obj1)
}
Static constructor – A static constructor is invoked only once for all instance of the class and it is invoked when we create the first instance of the class .The static constructor is used to initialize static field of the class the write the code which is executed only once.
Key points of static constructor
A static constructor does not contain any access modifier and also parameter less.
Static constructor is always public.
It cannot be call directly.
The syntax of the static constructor is given below:
Public class class1
{
Static class1()
{
Messagebox.show(“Static constructor”);
}
}

Private constructor – Private constructor is used to initialized the static member of the class .when a constructor is private , it is not possible for other classes to derive from this class.The sysntax of the private constructor is given below :
Public class class1
{
Private class1()
}

 



Saturday, February 6, 2016

Bind More than One Dropdownlist from DataBase using SqlDataReader

In this article I am going to explain how to bind multiple drop down list from single sqldatareader.

First I have created two table and one procedure. Run given below script in your Sql Server.


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sha_Country]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Sha_Country](
                [CountryId] [int] IDENTITY(1,1) NOT NULL,
                [CountryName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Sha_Country] ON
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (1, N'Afghanistan')
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (2, N'Brazil')
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (3, N'Cuba')
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (4, N'Egypt')
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (5, N'India')
SET IDENTITY_INSERT [dbo].[Sha_Country] OFF


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sha_Services]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Sha_Services](
                [ServiceID] [int] IDENTITY(1,1) NOT NULL,
                [ServiceName] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Sha_Services] ON
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (1, N'Service1')
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (2, N'Service2')
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (3, N'Service3')
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (4, N'Service4')
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (5, N'Service5')
SET IDENTITY_INSERT [dbo].[Sha_Services] OFF

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sha_GettwoList]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:                              Sharad Gupta
-- Create date: 6-Jan-2015
-- Description:      
-- =============================================
CREATE PROCEDURE [dbo].[sha_GettwoList]
AS
BEGIN
                -- SET NOCOUNT ON added to prevent extra result sets from
                -- interfering with SELECT statements.
                SET NOCOUNT ON;
 
                SELECT ServiceID,
                                ServiceName
                FROM sha_services
 
                SELECT CountryId,
                                CountryName
                FROM Sha_Country
END
'
END
GO

Now Here code for c# to bind two dropdown list from single SqlDataReader using NextResult() method.

 C# code

using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class DropDown : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetDropDownValues();
        }
    }
    private void GetDropDownValues()
    {
        SqlConnection con = new SqlConnection("data source=.;Database=test;uid=********;pwd=********");
        con.Open();
        SqlCommand cmd = new SqlCommand("sha_GettwoList", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows)// it is not necessity to check it returen true or false || true if one or more row otherwise false
        {
            ddlService.DataSource = dr;
            ddlService.DataTextField = "ServiceName";
            ddlService.DataValueField = "ServiceID";
            ddlService.DataBind();
            ddlService.Items.Insert(0, new ListItem("Select Services", "0"));
            dr.NextResult();// for next select statement
            if (dr.HasRows)
            {
                ddlCountry.DataSource = dr;
                ddlCountry.DataTextField = "CountryName";
                ddlCountry.DataValueField = "CountryId";
                ddlCountry.DataBind();
                ddlCountry.Items.Insert(0, new ListItem("Select Country", "0"));
            }
            else {
                ddlCountry.Items.Insert(0, new ListItem("Country Not Found", "0"));
            }
        }
        else{
            ddlService.Items.Insert(0, new ListItem("Services Not Found", "0"));
        }
    }
}

Source Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DropDown.aspx.cs" Inherits="DropDown" %>
<!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>
    <fieldSet>
    <legend>Multi DropDown List</legend>
    <table>
    <tr>
    <td>Services:</td>
    <td><asp:DropDownList ID="ddlService" runat="server"></asp:DropDownList> </td>
    </tr>
    <tr>
    <td>Country:</td>
    <td><asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList> </td>
    </tr>
    </table>
    </fieldSet>
    </div>
    </form>
</body>
</html>


OutPut:


Monday, February 1, 2016

When we use Server.Transfer

Most of developer confused with "Server.Transfer" and "Response.Redirect", when we use this one and when we use that one. I think you all have to read the difference between "Server.Transfer" and "Response.Redirect".
  • The "Response.Redirect " makes the round trip and "Server.Transfer" does not.
I think we all know what round trip does, but here, I explain little bit of  the round trip

I explain it by taking an example

Suppose you have one button in your "aspx" page, when you click on that button your page is post back, the button click event will be fired, basically browser send request to the server and server processes that request and then send back to browser.

(Note:  The Web applications use HTTP to build up communication between the Web browser and the Web server. HTTP is disconnected in nature, which implies that the life cycle of a Web page is only a single roundtrip. Each time a Web server reacts to a page demand, it crisply makes the assets required to make the page, sends the page to the asking for customer and annihilates the page assets from the server. Between two page demands, Web server and the customers are separated with one another, and estimations of page variables and controls are not saved over the page demands.),

the server processes any code you attached to the button click event, creates a new page with the latest state of the page, and sends it back to the browser). That's one round trip.

When you can use Server.Transfer
  • When you do not want to round trip , because Server.Transfer direct communicate to the server or say "Server.Transfer" it directly communicate with the server to change the page hence it saves a roundtrip in the whole process and in case of "Responce.Redirect"  it first sends the request for the new page to the browser then browser sends the request for the new page to the webserver then after your page changes.
  • When you want to transfer page on same server . Suppose you write the code Server.Transfer("www.google.com");  It will raise error , in this case you can use "Responce.Redirect".
  • When you do not want to update the clients url history list or current url.