Sunday 2 August 2015

What are the different validators in ASP.NET?

Validations are the most important part of websites and software. By using validations we can restrict users to enter any Invalid data into your database. There are many  validation techniques available do validate form data like JQUERY validations, server side validations. In Asp .Net microsoft has provided us great validation controls.  In this series of articles we will explore validation controls provided by microsoft.


  1. Required field Validator
  2. Range Validator
  3. Compare Validator
  4. Custom Validator
  5. Regular expression Validator
  6. Summary Validator

1.     Required field Validator
The RequiredFieldValidator is actually very simple, and yet very useful. You can use it to make sure that the user has entered something in a TextBox control.

Step1: Create TextBox control, Validation Control and Button.
Step2: Use ErrorMessage property of RequiredFieldValidator and enter message you want to display.
Step3: Use ControlToValidate property of RequiredFieldValidator and enter id of TextBox which you want to validate.
Step4: Use ForeColor property of RequiredFieldValidator and enter name of the color you want to use

<table border="0" cellpadding="0" cellspacing="0">
        <tbody><tr>
            <td>
                <b>Enter Your Name </b>
                <asp:textbox runat="server" id="txtTestForRequiredField">
            </asp:textbox></td>
        </tr>
        <tr>
            <td>
                <asp:requiredfieldvalidator id="RequiredFieldValidator1" forecolor="Red" errormessage="Please enter your name" controltovalidate="txtTestForRequiredField" runat="server">
            </asp:requiredfieldvalidator></td>
        </tr>
        <tr>
            <td>
                <asp:button id="Button1" text="Save" runat="server">
            </asp:button></td>
        </tr>
    </tbody></table>.




What is the difference between Server.Transfer and Response.Redirect?


In Server.Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser. This provides a faster response with a little less overhead on the server. The clients url history list or current url Server does not update in case of Server.Transfer.

Response.Redirect is used to redirect the user’s browser to another page or site. It performs trip back to the client where the client’s browser is redirected to the new page. The user’s browser history list is updated to reflect the new address.

What is ASP Dot Net?


It is a framework developed by Microsoft on which we can develop new generation web sites using web forms(aspx), MVC, HTML, JavaScript, CSS etc. Its successor of Microsoft Active Server Pages(ASP). Currently there is ASP.NET 4.5, which is used to develop web sites. There are various page extensions provided by Microsoft that are being used for web site development. Eg: aspx, asmx, ascx, ashx, cs, vb, html, XML etc.

What is delegate???

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Syntax of Delegate & Methods Declaration

Check below sample code for delegate declaration and methods declaration

public delegate int Delegatmethod(int a,int b);

public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x + y;
}
}

















If you observe above code I declared Delegatmethod method with two parameters which matching with methods declared in Sampleclass class.

Complete Example

public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();

DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
























Output

Whenever we run above code we will get output like as shown below


Add Result : 30
Sub Result : 10

What is the use of Delegates?

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

Delegates are two types

      -   Single Cast Delegates
      -  Multi Cast Delegates

Single Cast Delegates

Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates



Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list

Check below sample code for delegate declaration and methods declaration



Syntax of Multicast Delegate & Method Declaration

Check below sample code for multicast delegate declaration and methods declaration


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
If you observe above code I declared MultiDelegate method with void return type.

Complete Example


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output



Whenever we run above code we will get output like as shown below


Addition Value : 15
Subtraction Value : 5
Multiply Value : 50


how to create stored procedure using asp.net for beginner.



for example: first of all we have to create table.

Table- StudentInfo

SID
int
Name
Varchar(100)
Class
Varchar(100)
FatherName
Varchar(100)
Address
Varchar(200)
ContactNo
bigint

In which table  SID(columns) is an identity .
syntax here..

create table StudentInfo
(
SID                 int identity(1,1),
Name              varchar(100),
Class               varchar(100),
FatherName    varchar(100),
Address           varchar(200),
ContactNo.      bigint
)

execute in sql...

now we learn how to insert data using stored procedure.

first of all we should be know what is stored procedure.  please read my previous article in which i have written about procedure.

Now we  have to create stored procedure. when you create stored procedure you can use these two words proc/procedure for creating the procedure

Create proc sp_studentinfo
@Name      varchar(100),
@Class       varchar(100),
@FatherName  varchar(100),
@Address         varchar(200),
@Contact          bigint
as
      begin
             
          insert into StudentInfo(Name,Class,FatherName,Address,Contact) values(@Name,@Class,@FatherName,@Address,@Contact)

end

here studentinfo.aspx.cs page


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class student : System.Web.UI.Page
{
    SqlConnection con = new           SqlConnection(ConfigurationManager.AppSettings["ConString"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("sp_studentinfo", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Name",txtname.Text);
        cmd.Parameters.AddWithValue("@Class", txtclass.Text);
        cmd.Parameters.AddWithValue("@Address",txtaddress.Text);
        cmd.Parameters.AddWithValue("@FatherName",txtefname.Text);
        cmd.Parameters.AddWithValue("@Contact", txtmob.Text);
        con.Open();
        int i=cmd.ExecuteNonQuery();
        if (i == 1)
        {
            Label1.Text = "Data Successfully inserted...";
        }
        else
        {
            Label1.Text = "Try Again";
        }
        con.Close();

    }
}

here studentinfo.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="student.aspx.cs" Inherits="student" %>


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1
        {
            width: 100%;
        }
        .auto-style2
        {
            height: 23px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table class="auto-style1">
            <tr>
                <td>Name</td>
                <td>
                    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style2">Class</td>
                <td class="auto-style2">
                    <asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
                </td>
                <td class="auto-style2"></td>
            </tr>
            <tr>
                <td class="auto-style2">Father Name</td>
                <td class="auto-style2">
                    <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
                </td>
                <td class="auto-style2"></td>
            </tr>

            <tr>

                <td class="auto-style2">Address</td>
                <td class="auto-style2">
                    <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
                </td>
                <td class="auto-style2"></td>
            </tr>
            <tr>
                <td class="auto-style2">Contact</td>
                <td class="auto-style2">
                    <asp:TextBox ID="txtmob" runat="server"></asp:TextBox>
                </td>
                <td class="auto-style2"></td>
            </tr>
            <tr>
                <td class="auto-style2"></td>
                <td class="auto-style2"></td>
                <td class="auto-style2"></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </td>
                <td>&nbsp;</td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>