26 November 2013

Stored procedure in Sql server.?

Here I will explain about what is stored procedure is and advantages and disadvantages of stored procedures in sql server.

Description:

- A stored procedure is a group of sql statements that has been created and stored in the database.
- Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data.
- Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure

Sample of creating Stored Procedure

ALTER PROCEDURE PriceMaster
@ItemCode nvarchar(225),
@PriceType nvarchar(225),
@PriceDate nvarchar(225),
@PriceRef nvarchar(225),

AS
    insert into Price$ values(@ItemCode,@PriceType,@PriceDate,@PriceRef)
/* SET NOCOUNT ON */
RETURN

Differences between ExecuteReader, ExecuteNonQuery AND ExecuteScalar

In this article I will explain differences between executereader, executenonquery and executescalar in asp.net.

Description:

1.ExecuteNonQuery

ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations.This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SETstatements.

2.ExecuteScalar

Execute Scalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. It’s very fast to retrieve single values from database.

3.ExecuteReader

Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last.

Difference between DataReader and DataSet and DataAdapter in C#,ASP.NET?

In this article I will explain difference between datareader, dataset and dataadapter in asp.net and c#.

Description:

1.DataReader

- DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database.
- DataReader is used to iterate through resultset that came from server and it will read one record at a time because of that memory consumption will be less and it will fetch the data very fast when compared with dataset.
- Generally we will use ExecuteReaderobject to bind data to datareader.

Sample code of datareader will be like this

C# Code :

// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location FROM UserInformation", con);
SqlDataReader dr = cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}
}

2.DataSet

- DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables.
- It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.

C# Code :

// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}

3.DataAdapter

- DataAdapter will acts as a Bridge between DataSet and database.
- This dataadapter object is used to read the data from database and bind that data to dataset.
- Dataadapter is a disconnected oriented architecture.

 Check below sample code to see how to use DataAdapter in code

C# Code :

// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}


Difference between char,varchar and nvarchar in sql server

In this article I will explain what is the difference between char, varchar and nvarchar in SQL Server.

1.Char DataType

Char datatype which is used to store fixed length of characters. Suppose if we declared char(50) it will allocates memory for 50 characters.
Once we declare char(50) and insert only 10 characters of word then only 10 characters of memory will be used and other 40 characters of memory will be wasted.

2.varchar DataType

Varchar means variable characters and it is used to store non-unicode characters. It will allocate the memory based on number characters inserted.
Suppose if we declared varchar(50) it will allocates memory of 0 characters at the time of declaration.
Once we declare varchar(50) and insert only 10 characters of word it will allocate memory for only 10 characters.

3.nvarchar DataType

nvarchar datatype same as varchar datatype but only difference nvarchar is used to store Unicode characters and it allows you to store multiple languages in database.
nvarchar datatype will take twice as much space to store extended set of characters as required by other languages.

So if we are not using other languages then it’s better to use varchar datatype instead of nvarchar

Difference between bit,tinyint,smallint,int and bigint datatypes in SQL Server

In this article I will explain what is the difference between bit, tinyint, smallint, int and bigint datatypes in SQL Server.

Bit DataType

This datatype represents a single bit that can be 0 or 1.

tinyint DataType

This datatype represents a single byte which is used to store values from 0 to 255 (MinVal: 0, MaxVal: 255). Its storage size is 1 byte.

smallint DataType

This datatype represents a signed 16-bit integer which is used to store values from -2^15 (-32,768) through 2^15 - 1 (32,767) and its storage size is 2 bytes.

int DataType

This datatype represents a signed 32-bit integer which is used to store values from -2^31(-2,147,483,648) to 2 ^31-1(2,147,483,647). Its storage size is 4 bytes.

Bigint DataType

This datatype represents a signed 64-bit integer which is used to store values from -2^63 (-9223372036854775808) through 2^63-1 (9223372036854775807). Its storage size is 8 bytes.

Difference between Convert.tostring and .tostring() method Example

In this article I will explain differences between .tostring() and Convert.tostring() in asp.net.

Description:

The basic difference between them is “Convert.ToString(variable)” handles NULL values even if variable value become null but “variable.ToString()” will not handle NULL values it will throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.

Example :

//Returns a null reference exception for str.
string str;
object i = null;
str = i.ToString();

//Returns an empty string for str and does not throw an exception. If you dont
string str;
object i = null;
str = Convert.ToString(i);

Difference between Website and Web Application in ASP.NET

Here I will explain the differences between website and web application in asp.net.

Description:

Generally whenever we are trying to create new web project in visual studio we will fund two options ASP.NET Web Application and WebSite. What is the difference between these two which one we need to select to create project in asp.net?

It's choice of the people can go for web application or website we cannot say that which one is better because both is having advantages and disadvantages. Check below details for webaplication and website

Web Application

1. If we create any class files / functions those will be placed anywhere in the applications folder structure and it is precomplied into one single DLL.

2. In web application we have chance of select only one programming language during creation of project either C# or VB.NET.

3. Whenever we create Web Application those will automatically create project files (.csproj or .vbproj).

4. We need to pre-compile the site before deployment.

5. If we want to deploy web application project we need to deploy only .aspx pages there is no need to deploy code behind files because the pre-compiled dll will contains these details.

6. If we make small change in one page we need to re-compile the entire sites.

WebSite

1. If we create any class files/functions those will be placed in ASP.NET folder (App_Code folder) and it's compiled into several DLLs (assemblies) at runtime.

2. In website we can create pages in multi programming languages that means we can create one page code in C# and another page code in vb.net.

3. Web Sites won’t create any .csproj/.vbproj files in project

4. No need to recompile the site before deployment.

5. We need to deploy both .aspx file and code behind file.

6. If we make any code changes those files only will upload there is no need to re-compile entire site

Introduction to Object Oriented Programming Concepts (OOPS) in C#.net

I would like to discussion about Introduction to Object Oriented Programming Concepts (OOPS) in C#.net

OOPS Concepts :

  1. Class
  2. Object
  3. Encapsulation
  4. Abstraction
  5. Inheritance
  6. Polymorphism


A.Class:
 It is a collection of objects.

B.Object:
It is a real time entity.
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or a Student (object) can give the name or address. In pure OOP terms an object is an instance of a class

The above template describe about object Student
Class is composed of three things name, attributes, and operations

public class student
{
}
student objstudent=new student ();

According to the above sample we can say that Student object, named objstudent, has created out of the student class.

In real world you will often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles. In the software world, though you may not have realized it, you have already used classes. For example, the Textbox control, you always used, is made out of the Textbox class, which defines its appearance and capabilities. Each time you drag a Textbox control, you are actually creating a new instance of the Textbox class.

C.Encapsulation:

Encapsulation is a process of binding the data members and member functions into a single unit.

Example for encapsulation is class. A class can contain data structures and methods.
Consider the following class

public class Aperture
{
public Aperture ()
{
}
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0)
return 0;
return volume;
}
}

In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier

D.Abstraction:

Abstraction is a process of hiding the implementation details and displaying the essential features.

Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.

So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers

.Net has five access Specifiers

Public -- Accessible outside the class through object reference.

Private -- Accessible inside the class only through member functions.

Protected -- Just like private but Accessible in derived classes also through member
functions.

Internal -- Visible inside the assembly. Accessible through objects.

Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.

Let’s try to understand by a practical example:-

public class Class1
    {
        int  i;                                         //No Access specifier means private
        public  int j;                                        // Public
        protected int k;                             //Protected data
        internal int m;                        // Internal means visible inside assembly
        protected internal int n;                   //inside assembly as well as to derived classes outside assembly
        static int x;                                 // This is also private
        public static int y;                       //Static means shared across objects
        [DllImport("MyDll.dll")]
        public static extern int MyFoo();       //extern means declared in this assembly defined in some other assembly
        public void myFoo2()
        {
            //Within a class if you create an object of same class then you can access all data members through object reference even private data too
            Class1 obj = new Class1();
            obj.i =10;   //Error can’t access private data through object.But here it is accessible.:)
            obj.j =10;
            obj.k=10;
            obj.m=10;
            obj.n=10;
       //     obj.s =10;  //Errror Static data can be accessed by class names only
            Class1.x = 10;
         //   obj.y = 10; //Errror Static data can be accessed by class names only
            Class1.y = 10;
        }
    }

Now lets try to copy the same code inside Main method and try to compile
[STAThread]
        static void Main()
        {
           //Access specifiers comes into picture only when you create object of class outside the class
            Class1 obj = new Class1();
       //     obj.i =10; //Error can’t access private data through object.
            obj.j =10;
      //      obj.k=10;     //Error can’t access protected data through object.
            obj.m=10;
            obj.n=10;
       //     obj.s =10;  //Errror Static data can be accessed by class names only
            Class1.x = 10;  //Error can’t access private data outside class
         //   obj.y = 10; //Errror Static data can be accessed by class names only
            Class1.y = 10;
        }
What if Main is inside another assembly
[STAThread]
        static void Main()
        {
           //Access specifiers comes into picture only when you create object of class outside the class
            Class1 obj = new Class1();
       //     obj.i =10; //Error can’t access private data through object.
            obj.j =10;
      //      obj.k=10;     //Error can’t access protected data through object.
     //     obj.m=10; // Error can’t access internal data outside assembly
    //      obj.n=10; // Error can’t access internal data outside assembly

       //     obj.s =10;  //Errror Static data can be accessed by class names only
            Class1.x = 10;  //Error can’t access private data outside class
         //   obj.y = 10; //Errror Static data can be accessed by class names only
            Class1.y = 10;
        }
In object-oriented software, complexity is managed by using abstraction.
Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.

E.Inheritance:

Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.

Using System;
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                               
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}                              
Public class ChildClass: BaseClass
{
                               
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
 
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}

In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

The output of the above program is

Output:
  Base Class Constructor executed
  Child Class Constructor executed
  Write method in Base Class executed

this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes.

In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.

Syntax:  class ChildClassName: BaseClass
              {
                   //Body
              }

C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time
error: Class 'C' cannot have multiple base classes: 'A' and 'B'.

public class A
{
}
public class B
{
}
public class C : A, B
{
}

In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method().

Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talk about interfaces in our later article.

Using System;
Public class A
{
    Public void A_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class B: A
{
    Public void B_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class C: B
{
    Public void C_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
                 
    Public static void Main ()
    {
        C C1 = new C ();
        C1.A_Method ();
        C1.B_Method ();
        C1.C_Method ();
    }
}
When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class. We will talk about access modifiers in our later article.

Common Interview Question: Are private class members inherited to the derived class?

Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.

Using System;
Public class A
{
Public void M1 ()
{
}
Private void M2 ()
{
}
}

Public class B: A
{
Public static void Main ()
{
B B1 = new B ();
B1.M1 ();
//Error, Cannot access private member M2
//B1.M2 ();
}
}
Method Hiding and Inheritance We will look at an example of how to hide a method in C#. The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding.

If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.

Using System;
Public class Parent
{
    Public void Write ()
    {
        Console.WriteLine ("Parent Class write method");
    }
}
Public class Child: Parent
{
    Public new void Write ()
    {
        Console.WriteLine ("Child Class write method");
    }
    Public static void Main ()
    {
        Child C1 = new Child ();
        C1.Write ();
        //Type caste C1 to be of type Parent and call Write () method
        ((Parent) C1).Write ();
    }
}

F.Polymorphism:

When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.
Polymorphism is one of the fundamental concepts of OOP.

Polymorphism provides following features:

1.It allows you to invoke methods of derived class through base class reference during runtime.
2.It has the ability for classes to provide different implementations of methods that are called through the same name.

Polymorphism is of two types:

1.Compile time polymorphism/Overloading
2.Runtime polymorphism/Overriding

Compile Time Polymorphism

Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.

Runtime Time Polymorphism

Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.

When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same prototype.

Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.

Method overloading has nothing to do with inheritance or virtual methods.

Following are examples of methods having different overloads:

void area(int side);
void area(int l, int b);
void area(float radius);

Practical example of Method Overloading (Compile Time Polymorphism)

using System;

namespace method_overloading
{
    class Program
    {
        public class Print
        {
         
            public void display(string name)
            {
                Console.WriteLine ("Your name is : " + name);
            }

            public void display(int age, float marks)
            {
                Console.WriteLine ("Your age is : " + age);
                Console.WriteLine ("Your marks are :" + marks);
            }
        }
     
        static void Main(string[] args)
        {

            Print obj = new Print ();
            obj.display ("George");
            obj.display (34, 76.50f);
            Console.ReadLine ();
        }
    }
}

Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters.

When and why to use method overloading

Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.

You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.

Method overloading showing many forms.

using System;
namespace method_overloading_polymorphism
{
    Class Program
    {
        Public class Shape
        {
            Public void Area (float r)
            {
                float a = (float)3.14 * r;
                // here we have used function overload with 1 parameter.
                Console.WriteLine ("Area of a circle: {0}",a);
            }

            Public void Area(float l, float b)
            {
                float x = (float)l* b;
                // here we have used function overload with 2 parameters.
                Console.WriteLine ("Area of a rectangle: {0}",x);

            }
            public void Area(float a, float b, float c)
            {
                float s = (float)(a*b*c)/2;
                // here we have used function overload with 3 parameters.
                Console.WriteLine ("Area of a circle: {0}", s);
            }
        }
        Static void Main (string[] args)
        {
            Shape ob = new Shape ();
            ob.Area(2.0f);
            ob.Area(20.0f,30.0f);
            ob.Area(2.0f,3.0f,4.0f);
            Console.ReadLine ();
        }
    }
}

Things to keep in mind while method overloading

If you use overload for method, there are couple of restrictions that the compiler imposes.

The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.

There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.

Method Overriding:

Whereas Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by using virtual/override keywords.

Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.

Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
Example:

// Base class
public class BaseClass
{
public virtual void Method1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
public override void Method1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass();
objDC.Method1();
 // calling the baesd class method
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}

Output
---------------------

Derived Class Method

Derived Class Method

Constructors and Destructors:

Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
Constructors and destructors do not have return types nor can they return values.
References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
Constructors cannot be declared with the keyword virtual.
Constructors and destructors cannot be declared const, or volatile.
Unions cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects.
The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator.

Example of Constructor:

class C
{
       private int x;  
       private int y;
       public C (int i, int j)
       {
                 x = i;
                 y = j;
       }
       public void display ()  
       {
               Console.WriteLine(x + "i+" + y);
       }
}

Example of Destructor

class D
{
        public D ()
        {
            // constructor
        }      
        ~D ()
        {
           // Destructor
        }
}

Displaying “ Checkbox “ Field in every row in the Table In the Grid View

In this Discussion,i want to informing about Displaying “ Checkbox “ Field in every row in the Table In  “Grid View “ and Create a table Data without DataBase Creation and Displays in GridView.

->Drag and drop the Gridview and button controls from Toolbox in windows form.
->in the form,write the code in the button click event as like shown below :

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 GridViewWithChechBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
// Create Table Data in GridView without Database creation….

        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);

// display CheckBox Field in the Gridview….code

            DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
            dataGridView1.Columns.Add(chk);
            chk.HeaderText = "Check Data";
            chk.Name = "chk";
            dataGridView1.Rows[2].Cells[3].Value = true;

        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

Result is shown below like..




Displays “ ComboBox “ Field In GridView in C# and ASP.NET

In this Discussion,I explaining about Display “ ComboBox “  Field In GridView and also Create a table Data without DataBase Creation and Displays in GridView as image shown below….


-Drog and Drop one Gridview and one button control from ToolBox in Windows form,then write the code like shown below :

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 GridViewWithComboBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
<!-- Create a table Data without DataBase Creation and Displays in GridView…  -->(comment)  

   private void button1_Click(object sender, EventArgs e)    // button click event
        {
            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);

<!-- Below Code is for Display “ ComboBox “ Field in GridView -->(comment)

            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);
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}


ProgressBar Control in C#.Net

A ProgressBar control is used to represent the progress of operation that takes time to complete operation where a user has to wait for the operation to be finished.

Drag and drop ProgressBar Control and a button from toolbox on the window Form.
 

By default maximum value of ProgressBar is set 100 and minimum value is set 0 you can change this value.
Code:

Write code on button click event.
 
Double click on Button Click event.

private void button1_Click_1(object sender, EventArgs e)
{
            while (progressBar1.Value < 100)
                progressBar1.Value += 5;
}

Run the application :
 

When you click show button then Progress Bar will start.


 

25 November 2013

The Watermark jQuery plugin...

In this article I will explain how to set Watermark Text for HTML INPUT fields like TextBox, Password and TextArea using jQuery Watermark plugin.
The Watermark jQuery plugin has an optional property WaterMarkTextColor which can be used to set the color of the Watermark text.
The complete page HTML markup is provided below :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="WaterMark.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#txtUserName, #txtPassword, #txtDetails").WaterMark();
            $("#txtEmail").WaterMark({
                WaterMarkTextColor: '#8B8B8B'
            });
        });
    </script>
</head>
<body>
UserName:
<input type="text" id="txtUserName" title="Enter UserName"/><br/>
Password:
<input type="password" id="txtPassword" title="Enter Password"/><br/>
Email:
<input type="text" id="txtEmail" title="Enter Email"/><br/>
Details:
<textarea rows="3"cols="20" id="txtDetails" title="Enter Details"></textarea><br/>
</body>
</html>

Output :
Once cursor moves on Textbox , shows watermark text like " Enter UserName " as shown below :





23 November 2013

How to display serial number automatically in GridView in asp.net?

In this post we will discuss how to display a serial number column in gridview in asp.net.

Serial number will come as an index, it will start from 1 and will go on increasing 1 value for each row.

Here the code to bind a gridview will be same. Only thing will change is we need to another <ItemTemplate> like below:

<asp:GridView ID="GridView1" runat="server">
            <Columns>
                <asp:TemplateField HeaderText="Serial Number">
                    <ItemTemplate>
                        <%# Container.DataItemIndex + 1 %>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
</asp:GridView>

If you will write this code then the serial number column will come as like shown below...




Various types of joins in SQL Server 2008

In this post we will discuss about various types of joins in SQL Server 2008.
 The joins are like Equi-joins, Non Equi-joins, Self-joins, Cartesian-joins, Outer joins.

In order to retrive data from two or more tables based on logical relationship between the two tables, we require joins. Joins indicate how database should use data from one table to select the rows in another table.

There are different types of joins are there. These are like
1-Equi-joins
2-Non Equi-joins
3-Self-joins
4-Cartesian joins
5-Outer joins
        -Left Outer Joins
        -Right Outer Joins

1- Equi-joins:
It returns the specified columns from both of the tables, and returns only the rows for which an equal value in the join column.

For Example:
SELECT E.EMPNO,E.ENAME,E.SAL,E.DEPTNO,
D.DEPTNO,D.DNAME,D.LOC,FROM EMP E
INNER JOIN DEPT D ON E.DEPTNO=D.DEPTNO

2- Non Equi-joins:
Here you can join values in two columns that are not equal. The same operators can be used for equijoins can be used here in case of non equijoins.

For Example:
SELECT E.EMPNO,E.ENAME,E.SAL,
 S.SALGRADE,S.LOWSAL,S.HISAL
 FROM EMP E INNER JOIN SALGRADE S
ON E.SAL BETWEEN S.LOSAL AND S.HISAL

3- Self-joins:
If a table has a reflexive relationship in the database, you can join it to itself automatically, This is also known as self joins.

For Example:
SELECT DISTINCT E.EMPNO,E.ENAME,E.SAL,E.DEPTNO,
FROM EMP E INNER JOIN EMP M
ON E.EMPNO=M.MGR

4- Cartesian joins:
If the cartesian join have a where clause ,its behaves as a n innerjoin.
If the cartesian join that doesnot have a where clause,it produces the cartesian product of the tables involved in the joins. The size of the cartesian product result set is the number of rows in the first tables multiplied by the no of rows in the second table. This is also known as cross join.

For Example:
SELECT E.EMPNO,E.ENAME,E.SAL,E.DEPTNO,
D.DEPTNO,D.DNAME,D.LOC FROM EMP E CROSS JOIN DEPT D
 
5- Outer joins:
By default, when we join multiple tables using innerjoin  what we get is the matching data from the two tables, if we want to include the data rows in the resultset that donot have a match in the joined tables, we can use outer join.

The outer join is basically devided into 3 types like
-Left Outer join
-Right Outer join
-Full Outer join

-Left Outer join:
We use the  Left Outer join to get the matching information plus the unmatched information from the Left hand side table.

For Example:
SELECT E.EMPNO,E.ENAME,E.SAL,E.DEPTNO,
D.DEPTNO,D.DNAME,D.LOC,FROM EMP E
LEFT OUTER JOIN DEPT D ON E.DEPTNO=D.DEPTNO

-Right Outer join:
we use the Right Outer join to get the matching information plus the unmatched information from the Right hand side table.

For Example:
SELECT E.EMPNO,E.ENAME,E.SAL,E.DEPTNO,
D.DEPTNO,D.DNAME,D.LOC,FROM EMP E
RIGHT OUTER JOIN DEPT D ON E.DEPTNO=D.DEPTNO

-Full Outer join:
Suppose we have unmatched information in both the sides we cannot retrive it at the same time to over come this in the ANSI style of join statement they have introduced Full Outer join.

For Example:
SELECT E.EMPNO,E.ENAME,E.SAL,E.DEPTNO,
D.DEPTNO,D.DNAME,D.LOC,FROM EMP E
Full OUTER JOIN DEPT D ON E.DEPTNO=D.DEPTNO

21 November 2013

More Examples of JQuery Selectors


1.$("*") :  - used to select all elements

Example :
      <!DOCTYPE html>
<html>
  <head>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
       </script>
       <script>
                  $(document).ready(function(){
                            $("button").click(function(){
                                   $("*").hide();
                             });
                  });
       </script>
   </head>
   <body>
           <h2>This is a heading</h2>
           <p>This is a paragraph.</p>
            <p>This is another paragraph.</p>
            <button>Click me</button>
   </body>
</html>

Result :
If Once click on "Click me" button,then all elements are hidden.


 2.$("p.intro") : 

              -used to select all elemnts  with class="intro".

Example :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p.intro").hide();
  });
});
</script>
</head>
<body>
<h2 class="intro">This is a heading</h2>
<p class="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

Result :
If once click on button, elements are hide whichever class="intro" as shown below...

3.$("ul li:first") :

                        used to select the first <li> element of the first <ul>.
Example :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("ul li:first").hide();
  });
});
</script>
</head>
<body>
<p>List 1:</p>
  <ul>
    <li>Coffee</li>
    <li>Milk</li>
    <li>Tea</li>
  </ul>

<p>List 2:</p>
<ul>
  <li>Coffee</li>
  <li>Milk</li>
  <li>Tea</li>
</ul>
<button>Click me</button>
</body>
</html>

Result :
If click button,whichever <li> elements are first position in <ul> tag are hide as shown below...


4. $("[href]") :

                     used to select all elements with an href attribute.

Example:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("[href]").hide();
  });
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><a href="http://www.w3schools.com/html/">HTML Tutorial</a></p>
<p><a href="http://www.w3schools.com/css/">CSS Tutorial</a></p>
<button>Click me</button>
</body>
</html>

Result :
If once click button,then all href related elements are hide as shown below:


5.$("tr:even") :

                      - select all even <tr> elements.
Example :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("tr:even").css("background-color","yellow");
});
</script>
</head>
<body>
<h1>Welcome to My Web Page</h1>
<table border="1">
<tr>
  <th>Company</th>
  <th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbköp</td>
<td>Sweden</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
</table>
</body>
</html>

Result :
even type(0,2,4,.......n) position related <tr> elements shows with yellow backgroungcolor as shown below :

6.$("tr:odd") :

                      - select all odd <tr> elements.

Example :
-------------same code as per above programme--------------

replace the code of even with odd.

odd type(1,3,5,.......n) position related <tr> elements shows with yellow backgroungcolor as shown below :


Explain about jQuery selectors along with examples?

jQuery selectors are one of the most important parts of the jQuery library.

jQuery Selectors :

  • jQuery selectors allow you to select and manipulate HTML element(s).
  • jQuery selectors are used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more.

All selectors in jQuery start with the dollar sign and parentheses:  "   $()   ".

A. The element Selector :

  • The jQuery element selector selects elements based on the element name.
    You can select all <p> elements on a page like this:

    $("p")

    Example
    When a user clicks on a button, all <p> elements will be hidden:

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("p").hide();
      });
    });
    </script>
    </head>

    <body>
    <h2>This is a heading</h2>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <button>Click me</button>
    </body>
    </html>

    Result : 

    whenever click "Button",Two paragraph statements are hidden(because which statements are arranged with <p> tag.) as shown below:


B. The #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the element:

$("#test")

Example
When a user clicks on a button, the element with id="test" will be hidden:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#test").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<button>Click me</button>
</body>

</html>

Result :
When click " Button ",then last statement (i,e This is another paragraph) is hidden.because which statement is mentioned with id ,that one only hide as shown below :                                                                                



C.The .class Selector

The jQuery class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:

$(".test)

Example
When a user clicks on a button, the elements with class="test" will be hidden:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $(".test").hide();
  });
});
</script>
</head>
<body>

<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

Result :
When click " Button ",then first two statements are hidden.because which statements is mentioned with class in the tag ,those are only hide as shown below :