Tuesday, March 29, 2016

Check Uncheck all CheckBoxes in ASP.Net GridView using Javascript

In this article I am going to explain how to check and unchecked all check-box in asp.net grid view using JavaScript function

Code to check uncheck checkboxes

            <script type="text/javascript">
                function SelectAllCheckboxes(chk) {
                    $('#<%=TypeHeregidviewname.ClientID%>').find("input[id*='chkitem']:checkbox").each(function () {
                        if (this != chk) {
                            this.checked = chk.checked;
                        }
                    });
 
                }
        </script>

Code of Default..aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!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>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
            <script type="text/javascript">
                function SelectAllCheckboxes(chk) {
                    $('#<%=gvselectall.ClientID%>').find("input[id*='chkitem']:checkbox").each(function () {
                        if (this != chk) {
                            this.checked = chk.checked;
                        }
                    });
 
                }
        </script>
 
</head>
<body>
    <form id="form1" runat="server">
  
   <asp:GridView ID="gvselectall" runat="server" AutoGenerateColumns="false">
   <Columns>
 
  <asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" onclick="SelectAllCheckboxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkitem" runat="server"  />
</ItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Eval("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:Label ID="lblgender" runat="server" Text='<%#Eval("gender") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
 
   </Columns>
   </asp:GridView>
    </form>
</body>
</html>

Code of Default..aspx.cs

using System;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt  = new  DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("gender");
            DataRow rr = dt.NewRow();
            rr["name"] = "Sharad";
            rr["gender"] = "Male";
            dt.Rows.Add(rr);
            DataRow rr1 = dt.NewRow();
            rr1["name"] = "Varun";
            rr1["gender"] = "Male";
            dt.Rows.Add(rr1);
            DataRow rr2 = dt.NewRow();
            rr2["name"] = "Devesh";
            rr2["gender"] = "Male";
            dt.Rows.Add(rr2);
            DataRow rr3 = dt.NewRow();
            rr3["name"] = "Sudhir";
            rr3["gender"] = "Male";
            dt.Rows.Add(rr3);
            DataRow rr4 = dt.NewRow();
            rr4["name"] = "Swati";
            rr4["gender"] = "Female";
            dt.Rows.Add(rr4);
 
            gvselectall.DataSource = dt;
            gvselectall.DataBind();
 
        }
    }
}

Output



After Click on header check-box


Monday, March 28, 2016

Validate strong password using RegularExpressionValidator

In this article I am going to explain how to validate a user for entering strong password.

Validation Expression

ValidationExpression="^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,16}$"

Note
  • Must have at least a minimum of (8 characters) and not more than a maximum of (16 characters) as the length.
  •  Must have 1 numeric digits.
  • Must have 1 alphabet and 1 Special characters like {! @ # $ % ^ & *}
Code

<asp:TextBox ID="txtpassword" TextMode="Password" runat="server" ></asp:TextBox>
    <span style="color: #ff0033; width: auto;">*</span>
<asp:RequiredFieldValidator ID="rfvtxtpassword" ValidationGroup="S"  ControlToValidate="txtpassword" runat="server" ErrorMessage="Please Enter User Name"></asp:RequiredFieldValidator>
   <asp:RegularExpressionValidator ID="Regtxtpassword" runat="server" ValidationGroup="S"
                                Display="None" ErrorMessage="Password Message" ControlToValidate="txtpassword"
                                ValidationExpression="^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,16}$"></asp:RegularExpressionValidator>


for RegularExpressionValidator download ajaxtoolkit

Sunday, March 20, 2016

String function in SQL

In the last article, I was explain about 


Now In this article I am going to explain string function in SQL.

String Functions

The following are the string functions.

ASCII (s)

It returns the ASCII value of the left character in the given string.

Example

select ASCII ('A')              Ans: 65
select ASCII (.ABC')        Ans: 65


Char (n)

It returns the character representing the given ASCII value.

Example

select Char (66) Ans: B

Lower (str)

It converts string into lower case.


Example

select Lower ('SHARAD') Ans: sharad

Upper (str)

It converts string into upper case.

Example
select Upper ('sharad') Ans: SHARAD

Len (str)

It returns the length of the given string.

Example

select Len (‘Sharad’) Ans: 6

Left (str, n)

It returns specified 'n' no. of characters from the left side of the given string.

Example

select Left ('Sharad', 4) Ans: Shar
select * from Emp where Left (ename, 3) Ans: Sha

Right (str, n)

It returns specified n no. of characters from the right side of the given string.

Example

select Right ('Sharad', 4) Ans: arad

Ques  Write a query to get a list of employees whose names end with the character 'rd'?
Ans select * from Emp where Right (ename, 2)='RD'


Ques Write a query to get a details of employees whose names 3rd & 4th characters are 'IT'?
Ans select * from Emp where Right (Left (ename), 4), 2)='IT'


Substring (s, START, length)

It returns a part of the string from the given string 's', From the specified start character and no. of characters specified as length.
Example

select Substring ('Hello', 1, 3)  Ans Hel
select Substring ('Hello', 2, 3) Ans ell


Ques Write a query to get a details of employees whose names 3rd & 4th characters are 'IT'?
Ans select * from Emp where Substring (ename, 3, 2)='IT'

Reverse (str)

It returns the given string in the reverse order.

Example
select Reverse ('shri') Ans: irhs

LTRIM (str)

It returns a string length eliminating any empty characters if present in the left side of the given string.

Example

select Len ('..shar')      Ans: 6
select LTRIM ('..shar') Ans: 4


RTRIM (str)

It returns a string length eliminating any empty characters if present in the right side of the given string.

Example

select Len ('Shar..')     Ans: 4
select RTRIM ('Shar..') Ans: 4


NOTE

RTRIM (str) function is not much useful because any empty characters in the end of the string is not considered.

Replace (str, search, replace)

It returns a new string by replacing each occurrences of the ‘search’ character with ‘replace’ character in the given string 'str'.

Example

select Replace ('Hello', 'L', 'K') Ans: HeKKo

Ques Write a select statement which retrieves the details of the customers whose name is 'SHARAD GUPTA'?
Ans select * from Emp where Replace (ename, ' ', '') Ans: SHARADGUPTA


CharIndex (search, str [,start]

It is used for finding the index position of the search character within the given string 's'.

Example
select CharIndex ('E', 'Hello')                 Ans: 2
select CharIndex ('o', 'Hello World')     Ans: 5
select CharIndex ('o', 'Hello World', 6) Ans: 8


NOTE

1 In the above case even if the string contains multiple ‘o’ characters in it, it always search and returns the index of the first character because the search starts from the first character.
2  'Start' is used for specifying the location from where the search has to be started.
select CharIndex ('X', 'Hello') Ans: 0
 

Ques Write a query to get the list of all the employees whose name contains character 'M' in them?
Ans select * from Emp where CharIndex ('M', ename) > 0


STUFF (str, start, length, Replace)

It replaces the given string with the Replace string from the specified starting character to the no. of characters specified as length.

Example

select STUFF (‘AXXBXXC’, 2, 2, ‘ZZ’)             Ans: AZZBXXC
select STUFF (‘AXXBXXC’, 2, 2, ‘MNO’)        Ans: AMNOBXXC


SOUNDEX (str)

The function returns a 4 digit alphanumeric string for each given string value.

Example
select Soundex ('color')                    Ans: C460
select Soundex ('colour')                 Ans: C460


1 It performs the calculation in the way the strings are sounded (or) pronounced.
2 We can make use of this function to perform comparisons between two strings which are sounded in the same way but has different spelling.

Like

select * from Emp where Soundex (ename) = Soundex ('Smyth')

NOTE


While applying the Soundex function it has to be applied on both sides of the
condition.

Friday, March 18, 2016

Function in SQL

These are provided for retrieving the information from the tables in various scenarios. They are 2 types
  1. Single Row Functions
  2. Group function
Single Row Functions

These functions execute once for each row that is present in the table i.e. if the table has '0' row it execute 'zero' times or 'n' rows it execute 'n' times.

Group function

These functions take a Group of rows into consideration & returns a single value a single value as an O/P i.e. if the table contains 'zero' or 'n' row it executes once & returns an O/P.
A function can be used in 2 different ways
  1. Columns list of a select statement  : like select name, len (ename) from Emp
  2. Condition of a select statement : like select * from Emp where len (name) = 5
Syntax of calling function

Select <function name> ([argument list]) [from <Tname> <condition>]

Note
From is optional if the argument does not contain any column name in it.

Example
  • Select len ('sharad')
  • Select len (ename) from Emp
Single Row Functions
  • Arithmetic functions
  • String functions
  • Date functions
  • Conversion functions
  • System function
Arithmetic  Functions

The following are the arithmetic function

ABS (n)

It returns the absolute value of the given n

Example:

1
 select ABS (15)   Ans: 15
2 select ABS (-15) Ans: 15

Sign(n)


It returns 1 if the given n is > 0 (or)
It returns 0 (zero) if the given n is = 0 (or)
It returns -1 if the given n is < 0.

Example


select sign (100)       Ans: 1
select sign (0)           Ans: 0
select sign (-100)     Ans: -1

Ceiling (n) 

It returns the least integer that is greater than the given n.


Example

select Ceiling (15.3) Ans: 16
select Ceiling (-15.3) Ans: -15
 

Floor (n)

It returns the highest integer less than the given number n.

Example

select Floor (15.6) Ans: -15
select Floor (-15.6) Ans: -16


Round (n, size [,funValue]

It returns the given n value rounded with specified decimals as size.

Example

select Round (156.678, 2) Ans 156.68
select Round (156.678, 0) Ans 157
select Round (156.678,-1) Ans 160
select Round (156.678,-3) Ans 0


The size can be negative value also. If it is negative, the rounding is performed before the decimal.
 

156678


The function value which is an optional parameter can be anything greater than '0' If it is used the function behaves as Truncate. So it will cut if the values but will not round them.

Example


select Round (156.678, 2, 1) Ans 156.67
select Round (156.678,-1, 1) Ans 150
select Round (156.678,-2, 1) Ans 100


PI ()
It returns the constant value of PI.


Example

select Pi () Ans: 3.14159263
select Round (Pi (), 2) Ans: 3.14


Power (n, m)

It returns the value of n power m.

Example

select Power (2,3) Ans: 8
select Power (3,4) Ans: 81


Square (n)

It returns the square of the given 'n'.

Example

select Square (2) Ans: 4

Sqrt (n)

It returns the square root of the given 'n'.

Example

select Sqrt (4) Ans: 2

Log (n)

It returns the natural logarithmic value of the given 'n' i.e. base 'e'

Example

select Log (10)
select Log10 (n)  Ans: It returns the logarithmic value of given ‘n’ to base 10.


Rand ([seed])

It returns a random no. ranging between 0.0 to 1 for each time it is executed.

Example

select Rand () Ans: 0.8077, 0.5377, etc.
select Rand () * 50 Ans: 42.172 ……….upto 50

If we want to generate a random no. between 1 and specified upper limit, multiply the function with the upper limit value and round it as following.


Example

select Rand () * 50
select Round (Rand () * 50, 0)

The optional parameter seed can be used for repeating the value one more time because for a given seed if always returns the same value. If the seed changes the value also changes.

NOTE
The Arithmetic functions provide with all the trigonometric functions like Sin, Cos, Tan, etc for which we need to provide the degrees as 'n' value.


In the next article we will discuss about string function.

Wednesday, March 16, 2016

What is delegate in c#?



Delegate is a user defined data type, it is used to store the reference on method. C# delegate work same as c language pointer.

Use of the delegate: Use of the delegate is that when you have two or more methods with same name and same signature and call all the method with single object.

The example of the delegate is given below: 

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

namespace WindowsFormsApplication8
{
    public delegate int mydel(int x, int y);
   public class Class1
    {
        public int add(int a, int b)
        {
            return a + b;
        }

        public int sub(int a, int b)
        {
            return a - b;
        }
    }
}

.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 WindowsFormsApplication8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Class1 obj = new Class1();
            mydel del = obj.add;
            int i = del(10, 20);
            MessageBox.Show(i.ToString());
            mydel del1 = obj.sub;
            int j = del1(20, 10);
            MessageBox.Show(j.ToString());
        }
    }
}
Output :
30
10




Types of delegate:
 
There are two types of delegate –
-Single cast delegates
-Multi cast delegates
Single cast Delegate – single cast delegate hold the address of single method like as explained in the above example.

Multicast Delegate - multicast delegate is used to hold the address of multiple methods, for this work we will use overloaded += operator and remove the address from delegate we use overloaded operator -=
Multicast Delegates will work for those methods which have return type only void.
The example of the Multicast delegates is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication9
{
    public delegate void mydel(int a, int b);
    public class Class1
    {
        public void add(int x, int y)
        {
            MessageBox.Show("addition value"+(x+y).ToString());
        }
        public void sub(int x, int y)
        {
            MessageBox.Show("subtraction value" + (x - y).ToString());
           
        }
        public void mul(int x, int y)
        {
            MessageBox.Show("multly value" + (x * y).ToString());
        }
    }
}


.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 WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Class1 obj = new Class1();
            mydel del = Class1.add;
            del += Class1.sub;
            del += Class1.mul;
            del(10, 5);



        }
    }
}

Output:
addition value : 15
subtraction value : 5
multiply value : 50