Pages

22 Sept 2013

JavaScript Operators With HTML

What is an operator?

Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. JavaScript language supports following type of operators.
  • Arithmetic Operators
  • Comparision Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators
Lets have a look on all operators one by one.

The Arithmatic Operators:

There are following arithmatic operators supported by JavaScript language:
Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
+Adds two operandsA + B will give 30
-Subtracts second operand from the firstA - B will give -10
*Multiply both operandsA * B will give 200
/Divide numerator by denumeratorB / A will give 2
%Modulus Operator and remainder of after an integer divisionB % A will give 0
++Increment operator, increases integer value by oneA++ will give 11
--Decrement operator, decreases integer value by oneA-- will give 9
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
To understand these operators in better way you can Try it yourself.

The Comparison Operators:

There are following comparison operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
==Checks if the value of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
!=Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.
To understand these operators in better way you can Try it yourself.

The Logical Operators:

There are following logical operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
&&Called Logical AND operator. If both the operands are non zero then then condition becomes true.(A && B) is true.
||Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.(A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is false.
To understand these operators in better way you can Try it yourself.

The Bitwise Operators:

There are following bitwise operators supported by JavaScript language
Assume variable A holds 2 and variable B holds 3 then:
OperatorDescriptionExample
&Called Bitwise AND operator. It performs a Boolean AND operation on each bit of its integer arguments.(A & B) is 2 .
|Called Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments.(A | B) is 3.
^Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.(A ^ B) is 1.
~Called Bitwise NOT Operator. It is a is a unary operator and operates by reversing all bits in the operand.(~B) is -4 .
<<Called Bitwise Shift Left Operator. It moves all bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc.(A << 1) is 4.
>>Called Bitwise Shift Right with Sign Operator. It moves all bits in its first operand to the right by the number of places specified in the second operand. The bits filled in on the left depend on the sign bit of the original operand, in order to preserve the sign of the result. If the first operand is positive, the result has zeros placed in the high bits; if the first operand is negative, the result has ones placed in the high bits. Shifting a value right one place is equivalent to dividing by 2 (discarding the remainder), shifting right two places is equivalent to integer division by 4, and so on.(A >> 1) is 1.
>>>Called Bitwise Shift Right with Zero Operator. This operator is just like the >> operator, except that the bits shifted in on the left are always zero,(A >>> 1) is 1.
To understand these operators in better way you can Try it yourself.

The Assignment Operators:

There are following assignment operators supported by JavaScript language:
OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assigne value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.
To understand these operators in better way you can Try it yourself.

Miscellaneous Operator

The Conditional Operator (? :)

There is an oprator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax:
OperatorDescriptionExample
? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y
To understand this operator in better way you can Try it yourself.

The typeof Operator

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
Here is the list of return values for the typeof Operator :
TypeString Returned by typeof
Number"number"
String"string"
Boolean"boolean"
Object"object"
Function"function"
Undefined"undefined"
Null"object"

JavaScript Variables and DataTypes, With HTML

JavaScript DataTypes:
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.

JavaScript allows you to work with three primitive data types:

Numbers eg. 123, 120.50 etc.

Strings of text e.g. "This text string" etc.

Boolean e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value.

In addition to these primitive data types, JavaScript supports a composite data type known as object. We will see an object detail in a separate chapter.

Note: Java does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

JavaScript Variables:
Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows:

<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows:

<script type="text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or later point in time when you need that variable as follows:

For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable you can assign a value the time of initialization as follows:

<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note: Use the var keyword only for declaration or initialization.once for the life of any variable name in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

To understand variables in better way you can Try it yourself.

JavaScript Variable Scope:
The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code.

Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Following example explains it:

<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
   var myVar = "local";  // Declare a local variable
   document.write(myVar);
}
//-->
</script>
This produces the following result:

local
To understand variable scope in better way you can Try it yourself.

JavaScript Variable Names:
While naming your variables in JavaScript keep following rules in mind.

You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.

JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one.

JavaScript variable names are case sensitive. For example, Name and name are two different variables.

20 Sept 2013

JavaScript Placement in HTML File

There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are following most preferred ways to include JavaScript in your HTML file.

Script in <head>...</head> section.

Script in <body>...</body> section.

Script in <body>...</body> and <head>...</head> sections.

Script in and external file and then include in <head>...</head> section.

In the following section we will see how we can put JavaScript in different ways:

JavaScript in <head>...</head> section:

If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result:


To understand it in better way you can Try it yourself.

JavaScript in <body>...</body> section:

If you need a script to run as the page loads so that the script generates content in the page, the script goes in the <body> portion of the document. In this case you would not have any function defined using JavaScript:

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
This will produce following result:

Hello World
This is web page body
To understand it in better way you can Try it yourself.

JavaScript in <body> and <head> sections:

You can put your JavaScript code in <head> and <body> section altogether as follows:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result:



Hello World

To understand it in better way you can Try it yourself.

JavaScript in External File :

As you begin to work more extensively with JavaScript, you will likely find that there are cases where you are reusing identical JavaScript code on multiple pages of a site.

You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.

Here is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute:

<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write your all JavaScript source code in a simple text file with extension ".js" and then include that file as shown above.

For example, you can keep following content in filename.js file and then you can use sayHello function in your HTML file after including filename.js file:

function sayHello() {
   alert("Hello World")
}

Enabling JavaScript in Browsers

All the modern browsers come with built-in support for JavaScript. Many times you may need to enable or disable this support manually.

This tutorial will make you aware the procedure of enabling and disabling JavaScript support in your browsers : Internet Explorer, Firefox and Opera.

JavaScript in Internet Explorer:
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer:

Follow Tools-> Internet Options from the menu

Select Security tab from the dialog box

Click the Custom Level button

Scroll down till you find Scripting option

Select Enable radio button under Active scripting

Finally click OK and come out

To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.

JavaScript in Firefox:
Here are simple steps to turn on or turn off JavaScript in your Firefox:

Follow Tools-> Options

from the menu
Select Content option from the dialog box

Select Enable JavaScript checkbox

Finally click OK and come out

To disable JavaScript support in your Firefox, you should not select Enable JavaScript checkbox.

JavaScript in Opera:
Here are simple steps to turn on or turn off JavaScript in your Opera:

Follow Tools-> Preferences

from the menu
Select Advanced option from the dialog box

Select Content from the listed items

Select Enable JavaScript checkbox

Finally click OK and come out

To disable JavaScript support in your Opera, you should not select Enable JavaScript checkbox.

Warning for Non-JavaScript Browsers:
If you have to do something important using JavaScript then you can display a warning message to the user using <noscript> tags.

You can add a noscript block immediately after the script block as follows:

<html>
<body>

<script language="javascript" type="text/javascript">
<!--
   document.write("Hello World!")
//-->
</script>

<noscript>
  Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>

19 Sept 2013

Javascript Syntax With HTML, Asp.net, Jquery

A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.

You can place the <script> tag containing your JavaScript anywhere within you web page but it is preferred way to keep it within the <head> tags.

The <script> tag alert the browser program to begin interpreting all the text between these tags as a script. So simple syntax of your JavaScript will be as follows

<script ...>
  JavaScript code
</script>
The script tag takes two important attributes:

language: This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.

type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".

So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">
  JavaScript code
</script>
Your First JavaScript Script:
Let us write our class example to print out "Hello World".

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
   document.write("Hello World!")
//-->
</script>
</body>
</html>
We added an optional HTML comment that surrounds our Javascript code. This is to save our code from a browser that does not support Javascript. The comment ends with a "//-->". Here "//" signifies a comment in Javascript, so we add that to prevent a browser from reading the end of the HTML comment in as a piece of Javascript code.

Next, we call a function document.write which writes a string into our HTML document. This function can be used to write text, HTML, or both. So above code will display following result:

Hello World!
To understand it in better way you can Try it yourself.

Whitespace and Line Breaks:
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.

Because you can use spaces, tabs, and newlines freely in your program so you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

Semicolons are Optional:
Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if your statements are each placed on a separate line. For example, the following code could be written without semicolons

<script language="javascript" type="text/javascript">
<!--
  var1 = 10
  var2 = 20
//-->
</script>
But when formatted in a single line as follows, the semicolons are required:

<script language="javascript" type="text/javascript">
<!--
  var1 = 10; var2 = 20;
//-->
</script>
Note: It is a good programming practice to use semicolons.

Case Sensitivity:
JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

So identifiers Time, TIme and TIME will have different meanings in JavaScript.

NOTE: Care should be taken while writing your variable and function names in JavaScript.

Comments in JavaScript:
JavaScript supports both C-style and C++-style comments, Thus:

Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.

Any text between the characters /* and */ is treated as a comment. This may span multiple lines.

JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.

The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.

Example:

<script language="javascript" type="text/javascript">
<!--

// This is a comment. It is similar to comments in C++

/*
 * This is a multiline comment in JavaScript
 * It is very similar to comments in C Programming
 */
//-->
</script>

Javascript Overview With Programming Language, HTML Asp.net, Jquery

What is JavaScript ?
JavaScript started life as LiveScript, but Netscape changed the name, possibly because of the excitement being generated by Java.to JavaScript. JavaScript made its first appearance in Netscape 2.0 in 1995 with a name LiveScript.

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.

The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers

The ECMA-262 Specification defined a standard version of the core JavaScript language.

JavaScript is:

JavaScript is a lightweight, interpreted programming language
Designed for creating network-centric applications
Complementary to and integrated with Java
Complementary to and integrated with HTML
Open and cross-platform
Client-side JavaScript:
Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.

It means that a web page need no longer be static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism features many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are valid they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user explicitly or implicitly initiates.

Advantages of JavaScript:
The merits of using JavaScript are:

Less server interaction: You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.

Immediate feedback to the visitors: They don't have to wait for a page reload to see if they have forgotten to enter something.

Increased interactivity: You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.

Richer interfaces: You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

Limitations with JavaScript:
We can not treat JavaScript as a full fledged programming language. It lacks the following important features:

Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.

JavaScript can not be used for Networking applications because there is no such support available.

JavaScript doesn't have any multithreading or multiprocess capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages.

JavaScript Development Tools:
One of JavaScript's strengths is that expensive development tools are not usually required. You can start with a simple text editor such as Notepad.

Since it is an interpreted language inside the context of a web browser, you don't even need to buy a compiler.

To make our life simpler, various vendors have come up with very nice JavaScript editing tools. Few of them are listed here:

Microsoft FrontPage: Microsoft has developed a popular HTML editor called FrontPage. FrontPage also provides web developers with a number of JavaScript tools to assist in the creation of an interactive web site.

Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in the professional web development crowd. It provides several handy prebuilt JavaScript components, integrates well with databases, and conforms to new standards such as XHTML and XML.

Macromedia HomeSite 5: This provided a well-liked HTML and JavaScript editor, which will manage their personal web site just fine.

Where JavaScript is Today ?
The ECMAScript Edition 4 standard will be the first update to be released in over four years. JavaScript 2.0 conforms to Edition 4 of the ECMAScript standard, and the difference between the two is extremely minor.

The specification for JavaScript 2.0 can be found on the following site: http://www.ecmascript.org/

Today, Netscape's JavaScript and Microsoft's JScript conform to the ECMAScript standard, although each language still supports features that are not part of the standard.

18 Sept 2013

JavaScript - Form Validation on HTML Page

Form validation used to occur at the server, after the client had entered all necessary data and then pressed the Submit button. If some of the data that had been entered by the client had been in the wrong form or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process and over burdening server.

JavaScript, provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions.

Basic Validation - First of all, the form must be checked to make sure data was entered into each form field that required it. This would need just loop through each field in the form and check for data.

Data Format Validation - Secondly, the data that is entered must be checked for correct form and value. This would need to put more logic to test correctness of data.

We will take an example to understand the process of validation. Here is the simple form to proceed :

<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
 <form action="/cgi-bin/test.cgi" name="myForm"
          onsubmit="return(validate());">
 <table cellspacing="2" cellpadding="2" border="1">
 <tr>
   <td align="right">Name</td>
   <td><input type="text" name="Name" /></td>
 </tr>
 <tr>
   <td align="right">EMail</td>
   <td><input type="text" name="EMail" /></td>
 </tr>
 <tr>
   <td align="right">Zip Code</td>
   <td><input type="text" name="Zip" /></td>
 </tr>
 <tr>
 <td align="right">Country</td>
 <td>
 <select name="Country">
   <option value="-1" selected>[choose yours]</option>
   <option value="1">USA</option>
   <option value="2">UK</option>
   <option value="3">INDIA</option>
 </select>
 </td>
 </tr>
 <tr>
   <td align="right"></td>
   <td><input type="submit" value="Submit" /></td>
 </tr>
 </table>
 </form>
 </body>
 </html>
Basic Form Validation:
First we will show how to do a basic form validation. In the above form we are calling validate() function to validate data when onsubmit event is occurring. Following is the implementation of this validate() function:

<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{

   if( document.myForm.Name.value == "" )
   {
     alert( "Please provide your name!" );
     document.myForm.Name.focus() ;
     return false;
   }
   if( document.myForm.EMail.value == "" )
   {
     alert( "Please provide your Email!" );
     document.myForm.EMail.focus() ;
     return false;
   }
   if( document.myForm.Zip.value == "" ||
           isNaN( document.myForm.Zip.value ) ||
           document.myForm.Zip.value.length != 5 )
   {
     alert( "Please provide a zip in the format #####." );
     document.myForm.Zip.focus() ;
     return false;
   }
   if( document.myForm.Country.value == "-1" )
   {
     alert( "Please provide your country!" );
     return false;
   }
   return( true );
}
//-->
</script>
To understand it in better way you can Try it yourself.

Data Format Validation:
Now we will see how we can validate our entered form data before submitting it to the web server.

This example shows how to validate an entered email address which means email address must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign:

<script type="text/javascript">
<!--
function validateEmail()
{

   var emailID = document.myForm.EMail.value;
   atpos = emailID.indexOf("@");
   dotpos = emailID.lastIndexOf(".");
   if (atpos < 1 || ( dotpos - atpos < 2 ))
   {
       alert("Please enter correct email ID")
       document.myForm.EMail.focus() ;
       return false;
   }
   return( true );
}
//-->
</script>

16 Sept 2013

Find control inside Asp.net GridView using jQuery

Labels: ASP.NET Grid View, GridView, jQuery, jQuery Codes, jQuery With ASP.NET

In this post, find jQuery code and explanation to "find control inside ASP.NET GridView". Why it is tricky? The reason is ID of control's placed inside ASP.NET Gridview get changed at the time of rendering. Till ASP.NET 3.5, the rendered client-side id is formed by taking the Web control's ID property and prefixed it with the ID properties of its naming containers.

In short, a Web control with an ID of txtFirstName can get rendered into an HTML element with a client-side id like "ctl00_MainContent_txtFirstName". And same is true for ASP.NET GridView.

Suppose, there is textbox and label control in gridview.
1
<ItemTemplate>
2
   <asp:TextBox ID="txtID" runat="server" />
3
   <asp:Label ID="lblID" runat="server" />
4
</ItemTemplate>
And when you run this, this is rendered as below.
1
<input name="gdRows$ctl02$txtID" type="text" id="gdRows_ctl02_txtID" />
2
<span id="gdRows_ctl02_lblID"></span>
As you notice, the ID of the control is changed. It is no more "txtID" or "lblID". Gridview ID and control number is added as prefix. So now how do you select these controls?

Related Post:
Download ASP.NET GridView & jQuery Tips and Tricks eBook
Common jQuery Mistakes
ASP.NET GridView and jQuery
To select all label which has ID as "lblID".
1
$('#<%=gdRows.ClientID %>').find('span[id$="lblID"]').text('Your text.');
To select particular label control out of all the labels which ends with "lblID".
1
var $arrL = $('#<%=gdRows.ClientID %>').find('span[id$="lblID"]');
2
var $lbl = $arrL[0];
3
$($lbl).text('Your text...');
Similarly, you can also find textbox. To select all textbox which has ID as "txtID".
1
$('#<%=gdRows.ClientID %>').find('input:text[id$="txtID"]').val('Your value.');
To select particular textbox control out of all the textboxes which ends with "lblID".
view sourceprint?
1
var $arrT = $('#<%=gdRows.ClientID %>').find('input:text[id$="txtID"]');
2
var $txt = $arrT[0];
3
$($txt).val('text...');

How to bind asp.net grid view using jquery

$(document).ready(function() {

        $.ajax({
            url: '../_AJAX/ajaxCall-InterestSubsidy.aspx',
            data: { 'MODE': 'BindGrid' },
            type: 'POST',
            dataType: 'json',
            success: function(result) {
                var reslk = result;

                $.each(result.Table1, function(index, res) {
                    $(".GridView1").append("<table><tr><td>" + res.StateId +
                    "</td><td>" + res.StateName +
                    "</td></tr></table>");

                });
            },
            error: function(e) {
            }
        });
    });
My grid view:

<asp:GridView ID="GridView1" runat="server" CssClass="GridView1">

</asp:GridView>

GridView column header merging in ASP.NET

Introduction
The ASP.NET GridView data control is a very rich tool for displaying tabular data in web applications and also it is easy to achieve a great degree of customization with this control. In this article, we will examine how to merge a grid view column header and highlight the grid cells for a timesheet application. There are several ways to achieve this, we are going to see one among them. Hope this will be useful for those who work with timesheet kind of applications.

Requirement  
We have a requirement to create an ASP.NET webpage to display the timesheet summary details in tabular format as shown in figure 1. Each Employee Name header should be split into three columns as In Time, Out Time, and Status. Personal leaves and weekend holiday cells should be highlighted with colors as shown below.


Figure 1.
Solution    
The above requirement can be achieved through the ASP.NET GridView data control. GridView row objects are created before the GridView control is rendered on to the page. Most cell formatting activities can be achieved by capturing the RowDataBound and RowCreated events. 

Using the code  
Let’s create a sample timesheet web page to explain a solution for this problem. To get this first we have to populate sample timesheet data using code. Please download the attached source code and go through the data manager class functionality to populate employee and timesheet data using data tables.

Next, we will bind timesheet data to a GridView control. Before binding we should customize the data source table as follows using employee and timesheet data. Refer to the following table and code. 


Figure 2.
Now we will see the code to populate the GridView. The following code reads the employee and timesheet data from the sample data tables and generates a new timesheet data table as shown in the above figure.    

private string _seperator = "|";

protected void btnShow_Click(object sender, EventArgs e)
{
  // Reading employee data
  DataTable employeeData = DataManager.GetEmployeeData();
  // Reading time sheet data for the employee for a data range
  DataTable timeSheetData = DataManager.GetTimeSheetData();

  // Creating a customized time sheet table for binding with data grid view
  var timeSheet = new DataTable("TimeSheet");

  timeSheet.Columns.Add("DENTRY" + _seperator + "");

  // creating colum header for each employee data
  foreach (DataRow item in employeeData.Rows)
  {
    string columnName = item["EMPLOYEENAME"].ToString().Trim();
    timeSheet.Columns.Add(columnName + _seperator + "InTime");
    timeSheet.Columns.Add(columnName + _seperator + "OutTime");
    timeSheet.Columns.Add(columnName + _seperator + "Status");
   }

   // setting start date
   DateTime currentDate = Convert.ToDateTime("05/21/2012");

   //creating 10 days time sheet data for each employee
   for (int i = 0; i < 9; i++)
   {
     var dataRow = timeSheet.NewRow();
     FillTimeSheetRow(timeSheetData, employeeData, currentDate, dataRow);
     timeSheet.Rows.Add(dataRow);
     currentDate = currentDate.AddDays(1);
   }

   //Binding time sheet table with data grid view
   timeSheetGrid.DataSource = timeSheet;
   timeSheetGrid.DataBind();
}

private void FillTimeSheetRow(DataTable timeSheetData, 
        DataTable employees, DateTime currentDate, DataRow dataRow)
{
     dataRow["DENTRY" + _seperator + 
             ""] = currentDate.ToString("dd-MMM-yyyy");

      foreach (DataRow row in employees.Rows)
      {
           string columnName = row["EMPLOYEENAME"].ToString().Trim();
           string employeeId = (row["EMPLOYEEID"]).ToString().Trim();

            var dayStatus = "";
            // updating status as holiday for week ends
             if (currentDate.DayOfWeek.ToString() == "Saturday" || 
                     currentDate.DayOfWeek.ToString() == "Sunday")
             {
                  dayStatus = "HDAY";
              }

              // Fetching time sheet entry for the current data from time sheet data
               DataRow[] result = timeSheetData.Select("EMPLOYEEID='" + employeeId + 
                     "' AND DENTRY='" + currentDate.ToShortDateString() + "'");

                if (result.Length != 0)
                {
                    string status = result[0]["STATUS"].ToString();
                    dataRow[columnName + "|InTime"] = result[0]["INTIME"].ToString();
                    dataRow[columnName + "|OutTime"] = result[0]["OUTTIME"].ToString();
                    dayStatus = status;
                }
                dataRow[columnName + "|Status"] = dayStatus;
            }
        }
    }
}


After modifying the timesheet data table, we have to capture two events (RowDataBound and RowCreated) for changing the cell background color and merging the column headers.

Changing the GridView cell background colors.
Before the timesheet GridView control can be rendered on to the page, we have to capture the RowDataBound event. And it is triggered whenever the GridViewRow object is bound to timesheet data. A GridviewRowEventArgs object is passed to the handler method, which will help us access properties of every row. After getting the row cells we can check for the cell text property and we can change the background color for that particular cell using the BackColor property. Refer to the following code snippet.

protected void timeSheetGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  //number of cells in the row
  int cellCount = e.Row.Cells.Count;

  //iterating through every cells and check for the status for each employees
  for (int item = 3; item < cellCount; item = item + 3)
  {
    if (e.Row.Cells != null)
    {
      var cellText = e.Row.Cells[item].Text;
      switch (cellText)
      {
       case "WDAY"://Working Day
        e.Row.Cells[item].VerticalAlign = VerticalAlign.Middle;
       break;
       case "LEAVE"://Leave
        e.Row.Cells[item].VerticalAlign = VerticalAlign.Middle;
        e.Row.Cells[item].BackColor = Color.FromArgb(255, 255, 000);
        e.Row.Cells[item - 1].BackColor = Color.FromArgb(255, 255, 000);
        e.Row.Cells[item - 2].BackColor = Color.FromArgb(255, 255, 000);
       break;
       case "HDAY"://Holiday
        e.Row.Cells[item].VerticalAlign = VerticalAlign.Middle;
        e.Row.Cells[item].BackColor = Color.FromArgb(255, 0, 0);
        e.Row.Cells[item - 1].BackColor = Color.FromArgb(255, 0, 0);
        e.Row.Cells[item - 2].BackColor = Color.FromArgb(255, 0, 0);
       break;
      }
    }
  }
}


2. Merging GridView column headers
Just like RowDataBound, the RowCreated event gets fired whenever a row in the GridView is created. This helps us code custom functionality to a grid row and allows to implement code to merge cell headers depending on the RowType of the GridviewRowEventArgs object arguments. After customization we can hide the default header row by making the Visible property false. Refer to the following code snippet:



protected void timeSheetGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
  //If row type= header customize header cells
  if (e.Row.RowType == DataControlRowType.Header)
  CustomizeGridHeader((GridView)sender, e.Row, 2);
}

private void CustomizeGridHeader(GridView timeSheetGrid, 
             GridViewRow gridRow, int headerLevels)
{
     for (int item = 1; item <= headerLevels; item++)
     {
        //creating new header row
        GridViewRow gridviewRow = new GridViewRow(0, 0, 
        DataControlRowType.Header, DataControlRowState.Insert);
        IEnumerable<IGrouping<string,>> gridHeaders = null;

        //reading existing header 
        gridHeaders = gridRow.Cells.Cast<tablecell>()
        .Select(cell => GetHeaderText(cell.Text, item))
        .GroupBy(headerText => headerText);

        foreach (var header in gridHeaders)
        {
            TableHeaderCell cell = new TableHeaderCell();

            if (item == 2)
            {
                cell.Text = header.Key.Substring(header.Key.LastIndexOf(_seperator) + 1);
            }
            else
            {
                cell.Text = header.Key.ToString();
                if (!cell.Text.Contains("DENTRY"))
                {
                    cell.ColumnSpan = 3;
                }
            }
            gridviewRow.Cells.Add(cell);
        }
        // Adding new header to the grid
        timeSheetGrid.Controls[0].Controls.AddAt(gridRow.RowIndex, gridviewRow);
    }
    //hiding existing header
    gridRow.Visible = false;
}

private string GetHeaderText(string headerText, int headerLevel)
{
    if (headerLevel == 2)
    {
        return headerText;
    }
    return headerText.Substring(0, headerText.LastIndexOf(_seperator));
}



Now we will see the rest of the code-behind for the GridView control:


<table>
<tbody><tr>
<td>
<asp:button id="btnShow" runat="server" 
      text="Show" onclick="btnShow_Click">
</asp:button></td>
</tr>
<tr>
<td><asp:panel id="pnlContent" scrollbars="Auto" 
    style="background-color: white; width: 980px; height: 500px; " runat="server">
<asp:gridview id="timeSheetGrid" runat="server" cellpadding="4" 
        forecolor="#333333" gridlines="Both" bordercolor="#738DA5" 
        cellspacing="1" width="100%" 
        onrowcreated="timeSheetGrid_RowCreated" 
        onrowdatabound="timeSheetGrid_RowDataBound">
   <editrowstyle backcolor="#999999">
   <footerstyle backcolor="#5D7B9D" 
          font-bold="True" forecolor="White">
   <headerstyle backcolor="#465c71" font-bold="False" 
      forecolor="White" wrap="false" font-size="Small">
   <pagerstyle backcolor="#284775" forecolor="White" 
          horizontalalign="Center">
   <rowstyle backcolor="white" forecolor="black" 
          wrap="false" font-size="Small">
   <selectedrowstyle backcolor="#E2DED6" font-bold="True" 
          forecolor="#333333">
   <sortedascendingcellstyle backcolor="#E9E7E2">
   <sortedascendingheaderstyle backcolor="#5216C8C">
   <sorteddescendingcellstyle backcolor="#FFFDF8">
   <sorteddescendingheaderstyle backcolor="#6F8DAE">
   </sorteddescendingheaderstyle>
   </sorteddescendingcellstyle>
   </sortedascendingheaderstyle>
   </sortedascendingcellstyle>
   </selectedrowstyle>
   </rowstyle>
   </pagerstyle>
   </headerstyle>
   </footerstyle>
   </editrowstyle>
   </asp:gridview>
   </asp:panel>
   </td>
</tr>
</tbody>
</table>

15 Sept 2013

SQL SERVER – Pass One Stored Procedure’s Result as Another Stored Procedure’s Parameter

Here is the question – How to Pass One Stored Procedure’s Result as Another Stored Procedure’s Parameter. Stored Procedures are very old concepts and every day I see more and more adoption to Stored Procedure over dynamic code. When we have almost all of our code in Stored Procedure it is very common requirement that we have need of one stored procedure’s result to be passed as another stored procedure’s parameter.

Let us try to understand this with a simple example. Please note that this is a simple example, the matter of the fact, we can do the task of these two stored procedure in a single SP but our goal of this blog post is to understand how we can pass the result of one SP to another SP as a parameter.

Let us first create one Stored Procedure which gives us square of the passed parameter.

-- First Stored Procedure
CREATE PROCEDURE SquareSP
@MyFirstParam INT
AS
DECLARE @MyFirstParamSquare INT
SELECT @MyFirstParamSquare = @MyFirstParam*@MyFirstParam
-- Additional Code
RETURN (@MyFirstParamSquare)
GO

Now let us create second Stored Procedure which gives us area of the circle.

-- Second Stored Procedure
CREATE PROCEDURE FindArea
@SquaredParam INT
AS
DECLARE @AreaofCircle FLOAT
SELECT @AreaofCircle = @SquaredParam * PI()
RETURN (@AreaofCircle)
GO

You can clearly see that we need to pass the result of the first stored procedure (SquareSP) to second stored procedure (FindArea). We can do that by using following method:

-- Pass One Stored Procedure's Result as Another Stored Procedure's Parameter
DECLARE @ParamtoPass INT, @CircleArea FLOAT
-- First SP
EXEC @ParamtoPass = SquareSP 5
-- Second SP
EXEC @CircleArea = FindArea @ParamtoPass
SELECT @CircleArea FinalArea
GO

You can see that it is extremely simple to pass the result of the first stored procedure to second procedure.

You can clean up the code by running the following code.

-- Clean up
DROP PROCEDURE SquareSP
DROP PROCEDURE FindArea
GO

SQL SERVER – How to INSERT data from Stored Procedure to Table – 2 Different Methods

SQL STORED PROCEDURE

“How do I insert the results of the stored procedure in my table?”

This question has two fold answers – 1) When the table is already created and 2) When the table is to be created run time. In this blog post we will explore both the scenarios together.

However, first let us create a stored procedure which we will use for our example.

CREATE PROCEDURE GetDBNames
AS
SELECT name, database_id
FROM sys.databases
GO

We can execute this stored procedure using the following script.

EXEC GetDBNames

Now let us see two different scenarios where we will insert the data of the stored procedure directly into the table.

1) Schema Known – Table Created Beforehand

If we know the schema of the stored procedure resultset we can build a table beforehand and execute following code.

CREATE TABLE #TestTable ([name] NVARCHAR(256), [database_ID] INT);
INSERT INTO #TestTable
EXEC GetDBNames
-- Select Table
SELECT *
FROM #TestTable;

The disadvantage of this code is that if due to any reason the stored procedure returns more or less columns it will throw an error.

2) Unknown Schema – Table Created at Runtime

There are cases when we do know the resultset of the stored procedure and we want to populate the table based of it. We can execute following code.

SELECT * INTO #TestTableT FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;',
'EXEC tempdb.dbo.GetDBNames')
-- Select Table
SELECT *
FROM #TestTableT;

The disadvantage of this code is that it bit complicated but it usually works well in the case of the column names are not known.

Just note that if you are getting error in this method enable ad hoc distributed queries by executing following query in SSMS.

sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

I will be interested to know which of the above method do you use in your projects? and why?

12 Sept 2013

Sending e-mail in asp.net using smtp gmail server

public string SendMail(string toList, string from, string ccList, string subject, string body)
{

    MailMessage message = new MailMessage();
    SmtpClient smtpClient = new SmtpClient();
    string msg = string.Empty;
    try
    {
        MailAddress fromAddress = new MailAddress(from);
        message.From = fromAddress;
        message.To.Add(toList);
        if (ccList != null && ccList != string.Empty)
            message.CC.Add(ccList);
        message.Subject = subject;
        message.IsBodyHtml = true;
        message.Body = body;
        smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
        smtpClient.Port = 587;
        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new System.Net.NetworkCredential("Your Gmail User Name", "Your Gmail Password");

        smtpClient.Send(message);
        msg = "Successful<BR>";
    }
    catch (Exception ex)
    {
        msg = ex.Message;
    }
    return msg;
}

11 Sept 2013

Validate Date of Birth is not greater than current date using jQuery

jQuery, jQuery DatePicker, jQuery UI, jQuery UI DatePicker

This is a common situation where Date of birth needs to validated against the current or today's date. I have to implement the same functionality for my project. I have used jQuery UI datepicker control to select date and textbox was read only, it was pretty easy to implement.

All I needed to do is to stop datepicker control to disable dates greater than today's date. jQuery UI datepicker control provides an option to set the max date. If its value is set to "-1d" then all the dates after current date will be disabled.

Note: I have set the year range statically but this can be set programmatically.

$(document).ready(function(){
  $("#txtDate").datepicker(
  {
  yearRange:
  '<%=(System.DateTime.Now.Year - 150).ToString()%>:
  <%=System.DateTime.Now.Year.ToString() %>',
  changeMonth:true,
  changeYear:true,

  maxDate: '-1d'
  });
});

Validate email address using jQuery

jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes

This is a very basic functionality to validate the email address. In this post, I will show you how to validate the email address using jQuery. To validate the email address, I have created a separate function which based on email address, returns true or false. Email address validation is done using regular expression.

Earlier I had posted about Validate Date format using jQuery, Validate Date using jQuery and Validate Phone numbers using jQuery. And in this post, find jQuery way to Validate email address.

The validateEmail() functions (created below) will accept a parameter which is nothing but the email address and using regex it validates the email address. If it is correct then it returns true, otherwise false.

function validateEmail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }
}​
One just need to make a call to this function to validate the email address. For demo, I have used on click event of button. But It can be used on blur event of textbox or any another event.
view sourceprint?

$(document).ready(function() {
   $('#btnValidate').click(function() {
        var sEmail = $('#txtEmail').val();
        if ($.trim(sEmail).length == 0) {
            alert('Please enter valid email address');
            e.preventDefault();
        }
        if (validateEmail(sEmail)) {
            alert('Email is valid');
        }
        else {
            alert('Invalid Email Address');
            e.preventDefault();
        }
    });
});

Validate phone numbers using jQuery

jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Validation

Now days registration forms have phone numbers as mandatory field. But how to validate the entered phone number is correct or not? In this post, I will show you how to validate the phone number using jQuery. To validate the phone number, I have created a function which based on input, returns true or false. It checks for the validity of phone number using regular expression.

//Code Starts

function validatePhone(txtPhone) {
    var a = document.getElementById(txtPhone).value;
    var filter = /^[0-9-+]+$/;
    if (filter.test(a)) {
        return true;
    }
    else {
        return false;
    }
}​
//Code Ends
The above regular expression allows only numerals and + or – signs. Based on your requirement you can modify this regular expression.

Now call this function to validate the phone number. For demo, I have used on blur event of textbox But It can be used on click on button or any another event. Based on the result, it updates the status in a span tag.
//Code Starts

$('#txtPhone').blur(function(e) {
   if (validatePhone('txtPhone')) {
       $('#spnPhoneStatus').html('Valid');
       $('#spnPhoneStatus').css('color', 'green');
   }
   else {
      $('#spnPhoneStatus').html('Invalid');
      $('#spnPhoneStatus').css('color', 'red');
   }
});
//Code Ends

10 Sept 2013

jQuery code to allow only numbers in textbox

 jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes

Below jQuery code snippets will allow only numbers in the textbox. However backspace and delete keys are also allowed. 

$(document).ready(function(){
   $("#<%= txtNumbers.ClientID%>").keydown(function(e)
   {
       if (e.shiftKey)
           e.preventDefault();
       else
       {
           var nKeyCode = e.keyCode;
           //Ignore Backspace and Tab keys
           if (nKeyCode == 8 || nKeyCode == 9)
               return;
           if (nKeyCode < 95)
           {
               if (nKeyCode < 48 || nKeyCode > 57)
                   e.preventDefault();
           }
           else
           {
               if (nKeyCode < 96 || nKeyCode > 105)
               e.preventDefault();
           }
       }
   });
});

jQuery code to check if all textboxes are empty with jQuery, jQuery Codes, jQuery Tips, jQuery Validation

Find jQuery code to check if all the input type 'text' element or textboxes are empty or not. This is quite useful for validation. This jQuery code loops through all the textboxes and check their value. If value is empty then it adds a red color border to let user know that this field is required.

$(document).ready(function() {
    $('#btnSubmit').click(function(e) {
        var isValid = true;
        $('input[type="text"]').each(function() {
            if ($.trim($(this).val()) == '') {
                isValid = false;
                $(this).css({
                    "border": "1px solid red",
                    "background": "#FFCECE"
                });
            }
            else {
                $(this).css({
                    "border": "",
                    "background": ""
                });
            }
        });
        if (isValid == false)
            e.preventDefault();
        else
            alert('Thank you for submitting');
    });
});​


HTML 

<table>
<tr>
    <td>First Name:
    </td>
    <td><input type='text' id='txtFName'/ >
    </td>
</tr>
<tr>
    <td>Last Name:
    </td>
    <td><input type='text' id='txtLName'/ >
    </td>
</tr>
<tr>
    <td>Age:
    </td>
    <td><input type='text' id='txtAge'/ >
    </td>
</tr>
<tr>
    <td>Email:
    </td>
    <td><input type='text' id='txtEmail'/ >
    </td>
</tr>
<tr>
    <td colspan="2" style='text-align:center;'><input type="button" id="btnSubmit" value=" Submit ">
    </td>
</tr>
</table>

6 Sept 2013

SQL SERVER – Difference between DISTINCT and GROUP BY – Distinct vs Group By

This question is asked many times to me. What is difference between DISTINCT and GROUP BY?

A DISTINCT and GROUP BY usually generate the same query plan, so performance should be the same across both query constructs. GROUP BY should be used to apply aggregate operators to each group. If all you need is to remove duplicates then use DISTINCT. If you are using sub-queries execution plan for that query varies so in that case you need to check the execution plan before making decision of which is faster.

Example of DISTINCT:
SELECT DISTINCT Employee, Rank
FROM Employees

Example of GROUP BY:
SELECT Employee, Rank
FROM Employees
GROUP BY Employee, Rank

Example of GROUP BY with aggregate function:
SELECT Employee, Rank, COUNT(*) EmployeeCount
FROM Employees
GROUP BY Employee, Rank

SQL SERVER – Stored Procedure – Clean Cache and Clean Buffer


Use DBCC FREEPROCCACHE to clear the procedure cache. Freeing the procedure cache would cause, for example, an ad-hoc SQL statement to be recompiled rather than reused from the cache. If observing through SQL Profiler, one can watch the Cache Remove events occur as DBCC FREEPROCCACHE goes to work. DBCC FREEPROCCACHE will invalidate all stored procedure plans that the optimizer has cached in memory and force SQL Server to compile new plans the next time those procedures are run.

Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache without shutting down and restarting the server. DBCC DROPCLEANBUFFERS serves to empty the data cache. Any data loaded into the buffer cache due to the prior execution of a query is removed.

DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFERS

5 Sept 2013

SQL SERVER – Union vs. Union All – Which is better for performance?

This article is completely re-written with better example SQL SERVER – Difference Between Union vs. Union All – Optimal Performance Comparison. I suggest all of my readers to go here for update article.

UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.

UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.

The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.

A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

Example:
Table 1 : First,Second,Third,Fourth,Fifth
Table 2 : First,Second,Fifth,Sixth

Result Set:
UNION: First,Second,Third,Fourth,Fifth,Sixth (This will remove duplicate values)
UNION ALL: First,First,Second,Second,Third,Fourth,Fifth,Fifth,Sixth,Sixth (This will repeat values)

SQL SERVER – Delete Duplicate Records – Rows

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.

DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

Watch the view to see the above concept in action:



4 Sept 2013

Simple Example of Cursor - Simple Example of Cursor

This is the simplest example of the SQL Server Cursor. I have used this all the time for any use of Cursor in my T-SQL.
DECLARE @AccountID INT
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE @getAccountID
DEALLOCATE @getAccountID

Query to Find ByteSize of All the Tables in Database - SQL Server

SELECT CASE WHEN (GROUPING(sob.name)=1) THEN 'All_Tables'
   ELSE ISNULL(sob.name, 'unknown') END AS Table_name,
   SUM(sys.length) AS Byte_Length
FROM sysobjects sob, syscolumns sys
WHERE sob.xtype='u' AND sys.id=sob.id
GROUP BY sob.name
WITH CUBE

SQL SERVER – Check If Column Exists in SQL Server Table

A very frequent task among SQL developers is to check if any specific column exists in the database table or not. Based on the output developers perform various tasks. Here are couple of simple tricks which you can use to check if column exists in your database table or not.

Method 1

IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'columnName' AND OBJECT_ID = OBJECT_ID(N'tableName'))
BEGIN
PRINT 'Your Column Exists'
END

For AdventureWorks sample database

IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'Name' AND OBJECT_ID = OBJECT_ID(N'[HumanResources].[Department]'))
BEGIN
PRINT 'Your Column Exists'
END

Method 2

IF COL_LENGTH('table_name','column_name') IS NOT NULL
BEGIN
PRINT 'Your Column Exists'
END

For AdventureWorks sample database

IF COL_LENGTH('[HumanResources].[Department]','Name') IS NOT NULL
BEGIN
PRINT 'Your Column Exists'
END

Method 3

IF EXISTS(
SELECT TOP 1 *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE [TABLE_NAME] = 'TableName'
AND [COLUMN_NAME] = 'ColumnName'
AND [TABLE_SCHEMA] = 'SchemaName')
BEGIN
PRINT 'Your Column Exists'
END

For AdventureWorks sample database

IF EXISTS(
SELECT TOP 1 *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE [TABLE_NAME] = 'Department'
AND [COLUMN_NAME] = 'Name'
AND [TABLE_SCHEMA] = 'HumanResources')
BEGIN
PRINT 'Your Column Exists'
END

jQuery Animations and Effects

You can slide elements, animate elements, and even stop animations in mid-sequence. To slide elements up or down: 

$("#myElement").slideDown("fast", function() {
 // do something when slide down is finished
}

$("#myElement").slideUp("slow", function() {
 // do something when slide up is finished
}

$("#myElement").slideToggle(1000, function() {
 // do something when slide up/down is finished
}

To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles, but instead of setting them instantly (as CSS or raw JavaScript would do), it does so gradually, animating the effect at the chosen speed: 

$("#myElement").animate(
 {
 opacity: .3,
 width: "500px",
 height: "700px"
 }, 2000, function() {
 // optional callback after animation completes
 }
);

Animation with jQuery is very powerful, and it does have its quirks (for example, to animate colors, you need a special plugin). It's worth taking the time to learn to use the animate command in-depth, but it is quite easy to use even for beginners.

3 Sept 2013

Showing and Hiding Elements with jQuery

The syntax for showing, hiding an element (or toggling show/hide) is: 

$("#myElement").hide("slow", function() {
 // do something once the element is hidden
}

$("#myElement").show("fast", function() {
 // do something once the element is shown
}

$("#myElement").toggle(1000, function() {
 // do something once the element is shown/hidden
}

Remember that the "toggle" command will change whatever state the element currently has, and the parameters are both optional. The first parameter indicates the speed of the showing/hiding. If no speed is set, it will occur instantly, with no animation. A number for "speed" represents the speed in milliseconds. The second parameter is an optional function that will run when the command is finished executing.

You can also specifically choose to fade an element in or out, which is always done by animation:

$("#myElement").fadeOut("slow", function() {
 // do something when fade out finished
}

$("#myElement").fadeIn("fast", function() {
 // do something when fade in finished
}

To fade an element only partially, either in or out:

$("#myElement").fadeTo(2000, 0.4, function() {
 // do something when fade is finished
}

The second parameter (0.4) represents "opacity", and is similar to the way opacity is set in CSS. Whatever the opacity is to start with, it will animate (fadeTo) until it reaches the setting specified, at the speed set (2000 milliseconds). The optional function (called a "callback function") will run when the opacity change is complete. This is the way virtually all callback functions in jQuery work.

Dealing with Events in jQuery

Specific event handlers can be established using the following code: 

$("a").click(function() {
 // do something here
 // when any anchor is clicked
});

The code inside function() will only run when an anchor is clicked. Some other common events you might use in jQuery include: 

blur, focus, hover, keydown, load, mousemove, resize, scroll, submit, select. 

Adding, Removing, and Appending Elements and Content Using With Jquery

There are a number of ways to manipulate groups of elements with jQuery, including manipulating the content of those elements (whether text, inline elements, etc). 

Get the HTML of any element (similar to innerHTML in JavaScript): 

var myElementHTML = $("#myElement").html();
// variable contains all HTML (including text) inside #myElement
If you don't want to access the HTML, but only want the text of an element:
var myElementHTML = $("#myElement").text();
// variable contains all text (excluding HTML) inside #myElement

Using similar syntax to the above two examples, you can change the HTML or text content of a specified element: 
$("#myElement").html("<p>This is the new content.</p>");
// content inside #myElement will be replaced with that specified
$("#myElement").text("This is the new content.");
// text content will be replaced with that specified
To append content to an element:
$("#myElement").append("<p>This is the new content.</p>");
// keeps content intact, and adds the new content to the end
$("p").append("<p>This is the new content.</p>");
// add the same content to all paragraphs

jQuery also offers use of the commands appendTo(), prepend(), prependTo(), before(), insertBefore(), after(), and insertAfter(), which work similarly to append() but with their own unique characteristics that go beyond the scope of this simple tutorial. 

2 Sept 2013

Manipulating and Accessing CSS Class Names in Jquery

jQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this: 

$("div").addClass("content"); // adds class "content" to all <div> elements
$("div").removeClass("content"); // removes class "content" from all <div> elements
$("div").toggleClass("content");

// toggles the class "content" on all <div> elements (adds it if it doesn't exist, //
and removes it if it does)

You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an if statement. Here is an example: 

if ($("#myElement").hasClass("content")) {
 // do something here
}

You could also check a set of elements (instead of just one), and the result would return "true" if any one of the elements contained the class.

Selecting Elements in jQuery


The jQuery library allows you to select elements in your XHTML by wrapping them in $("") (you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery: 

$("div"); // selects all HTML div elements
$("#myElement"); // selects one HTML element with ID "myElement"
$(".myClass"); // selects HTML elements with class "myClass"
$("p#myElement"); // selects HTML paragraph element with ID "myElement"
$("ul li a.navigation");

// selects anchors with class "navigation" that are nested in list items
jQuery supports the use of all CSS selectors, even those in CSS3. Here are some examples of alternate selectors: 

$("p > a"); // selects anchors that are direct children of paragraphs
$("input[type=text]"); // selects inputs that have specified type
$("a:first"); // selects the first anchor on the page
$("p:odd"); // selects all odd numbered paragraphs
$("li:first-child"); // selects each list item that's the first child in its list
jQuery also allows the use of its own custom selectors. Here are some examples:
$(":animated"); // selects elements currently being animated
$(":button"); // selects any button elements (inputs or buttons)
$(":radio"); // selects radio buttons
$(":checkbox"); // selects checkboxes
$(":checked"); // selects checkboxes or radio buttons that are selected
$(":header"); // selects header elements (h1, h2, h3, etc.) 

1 Sept 2013

RowDataBound Event of GridView of asp.net with C#

Row DataBound event of GridView:-
Here we are binding the DropDownList in GridView and runtime set the dropdown selected value according to GridView Column.

Step1:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
             DataKeyNames="EmpID" onrowdatabound="GridView1_RowDataBound">
          <Columns>
          <asp:TemplateField  HeaderText="SetEno">
          <ItemTemplate>
          <asp:DropDownList ID="ddlEmpid" runat="server" Width="90%" DataSourceID="SqlDataSource1" DataTextField="EMPID"
                                DataValueField="EMPID"  >
          </asp:DropDownList>
          </ItemTemplate>              
         
          </asp:TemplateField>
       <asp:TemplateField HeaderText="Empid" Visible="false">
          <ItemTemplate>
          <asp:Label ID="lblEmpNo" runat="server" Text='<%# Eval("EmpNo") %>' />
          </ItemTemplate>
          </asp:TemplateField>
            <asp:BoundField DataField="EMPID" HeaderText="EmployeeID" ReadOnly="true"  />
            <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" />
            <asp:BoundField DataField="Address" HeaderText="Address" />
            <asp:BoundField DataField="Mobile" HeaderText="Mobile" />
                 
          </Columns>
        </asp:GridView>
Step2:-

    <asp:SqlDataSource ID="SqlDataSource1" runat="server"  ConnectionString="<%$ ConnectionStrings:mycon %>"
                SelectCommand="SELECT [EMPID] FROM EMPLOYEEID"></asp:SqlDataSource>
   
step3:-

public partial class GridViewDropDown : System.Web.UI.Page
{
    SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        string conection;
        conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
        con = new SqlConnection(conection);
     
            FillGrid();
         }
    protected void FillGrid()
    {
        SqlCommand cmd = new SqlCommand("select * from employee", con);
        con.Open();
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();
        con.Close();
    }


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {              
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlEmpid");
            Label lblEmpid = ((Label)e.Row.FindControl("lblEmpNo"));
          //  string y = (String)DataBinder.Eval(e.Row.DataItem, "FirstName");
            string x=lblEmpid.Text.ToString().Trim();
            ddl.SelectedValue = x;
        }
    }
   
}

GridView default Pager using CSS Class Styles in ASP.Net

In this article I will explain how to style the GridView default Pager using CSS Class Styles in ASP.Net.

Database
For this article I am making use of the Microsoft’s Northwind Database. Download and install instructions are provided in the link below

HTML Markup
The HTML Markup consists of an ASP.Net GridView. For the GridView I have enabled paging using the AllowPaging property and I have also specified on the OnPageIndexChanging event.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
    runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
    <Columns>
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" ItemStyle-Width="150px" />
        <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100px" />
    </Columns>
    <PagerStyle HorizontalAlign = "Right" CssClass = "GridPager" />
</asp:GridView>



Namespaces
You will need to import the following namespaces
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


Binding the GridView
Below is the code to bind the GridView with records from the Customers table of the Northwind database
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}

private void BindGrid()
{
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}


Styling the GridView Pager
In order to style the GridView Pager you need to follow the following
1. Add the following CSS classes to the page or the CSS file.
<style type="text/css">
    body
    {
        font-family: Arial;
        font-size: 10pt;
    }
    .GridPager a, .GridPager span
    {
        display: block;
        height: 15px;
        width: 15px;
        font-weight: bold;
        text-align: center;
        text-decoration: none;
    }
    .GridPager a
    {
        background-color: #f5f5f5;
        color: #969696;
        border: 1px solid #969696;
    }
    .GridPager span
    {
        background-color: #A1DCF2;
        color: #000;
        border: 1px solid #3AC0F2;
    }
</style>

2. Next you need to assign the Pager CSS Class to the Page using the PagerStyle-CssClass property as shown below

<PagerStyle HorizontalAlign = "Right" CssClass = "GridPager" />