Javascript Detect Null Object

There are many methods to check if an object is null in javascript, this post gives most of the options that can used to detect this.

Well, first of all, in JavaScript null is an object. There’s anothervalue for things that don’t exist, undefined. The DOM returns null foralmost all cases where it fails to find some structure in thedocument, but in JavaScript itself undefined is the value used.

Second, no, they are not directly equivalent.If you really want to check for null, do:

if (null == yourvar) // with casting
if (null === yourvar) // without casting

If you want to check if a variable exist

if (typeof yourvar != ‘undefined’) // Any scope
if (window['varname'] != undefined) // Global scope
if (window['varname'] != void 0) // Old browsers

If you know the variable exists but don’t know if there’s any valuestored in it:

if (undefined != yourvar)
if (void 0 != yourvar) // for older browsers

If you want to know if a member exists independent of whether it hasbeen assigned a value or not:

if (’membername’ in object) // With inheritance
if (object.hasOwnProperty(’membername’)) // Without inheritance

If you want to to know whether a variable autocasts to true:

Client and Serverside Button Click in ASP.Net

While I was going through the comments in this post here, someone asked a question around how button click function worked, so I thought I would write a post around this topic.

There are two types of click that can be associated with a button, one is a server side click function, i.e in a function in VB code that gets called, and there is a javascript click function, a function that gets called in javascript when a button is clicked on.
Javascript onclick function gets executed before the server side on click function.
Here are the methods of specifying both.

Javascript click function

1. in asp, specify the javascript to be called using the onclientclick attribute, what ever is specified in this attribute will be executed on the client side.

2. In the code behind, specify the javascritp to be called using the onclick attribute.

3. Using a library like JQuery, the onclick function can be specified like so
$(document).ready(function(){$(’#button’).click(function() {alert(’me’);});});
If you are doing some validation in the javascript and only want the server side click function to execute if the javascript validation is successful then you can return false in the javascript function called. If false is returned in the javascript function, the server side event is not executed.

Serverside Click Function

1. In the design view of the ASP, double click on a button, and a function similar to this should be generated

Private Sub
button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button.Click
End Sub

notice that the Handles part, this tells that code that this function is used to handle the click event of the button

2. In the source view, there are 2 drop down lists at the top, the left one allows selecting of the different form elements on the page, the right hand side allows viewing of the the functions available for each element. In the left, select the button, and then on the right, select Click, a sub similar to above should be created.

3. You can also specify the click function in the ASP and not have the Handles part in the code.

Private Sub
button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
End Sub

This would only work if the parameters specified matches the ones required for the button click event.

SQL statement to search inside stored procedure

Useful script for searching in stored procedures.

SELECT OBJECT_NAME(id)FROM syscommentsWHERE [text] LIKE ‘%searchtext%’AND OBJECTPROPERTY(id, ‘IsProcedure’) = 1GROUP BY OBJECT_NAME(id)

Ajax Dotnet AutoComplete Clear Cache

With the .net auto complete control, there is an attribute enablecache which tells the auto-complete to use caching or not. If this attribute is set to true, typing the same search text within a set number of seconds, instead of retrieving the data again from the database, the previous search results will be used.

Although caching is good in most cases, there are some cases where we need to clear the cache. For example, we have an auto-complete text-box, under this there are 2 check-boxes. Checking the check-box will change the search results. On clicking of the check-box we need to clear the cache of the auto-complete, so even though the same search text is enter, we need to do a complete new search again.

To do this, we can use the following java-script code on clicking of the check-box.

var autocompltebehaviour = $find(’autosearch’);
autocompletebehaviour._cache = null;

The id used in the $find function is the behaviour id attribute of the autocomplete textbox.
Using this method you can have both the caching of the autocomplete and no caching working at the same time.

Using Ajax for Web Application Development

Ajax web programming enables a web application development team to create a sit that allows users to perform certain functions without the need for redrawing or reloading an entire screen.


1. It offers site developers an extra level of innovation that can make a site easier to use for all visitors.

2. When implemented correctly, it gives users the feeling that a web application is more responsive than a traditional web site.

3. It can allow a business to give its site new functionality and new services to be used by partners or clients.

4. It can give parity to a business.

Things to be careful:

1. This type of web programming can make a site more difficult for visitors to use.The web is at its core a very user-friendly system, but Ajax can introduce new behaviors that people may not be ready for or may be confused by.This can cause visitors to leave your site quickly, without actually performing the tasks.

2. Ajax programming can create a host of other problems with which businesses should be concerned.

3. Ajax can open up a webserver to have an increased attack surface. This form of web programming unfortunately gives a hacker more ways to get into the server than there were before.The solution to this is to make sure that the web application development team is more vigilant about security and testing, and to constantly keep watch on the activity occurring on the site.

4. Different browsers read Ajax differently, the web application development team will have to do additional testing for accessibility.

What is RSS?

RSS, can be expanded as Rich Site Summary or Resource Description Framework Site Summary or Really Simple Syndication. RSS is a lightweight XML format for distributing regularly changed web contents among different web sites and users. A Web site can allow the users or other sites to publish some of its content by creating an RSS feeds.

Benefits of RSS Feeds

RSS allows the users to easily stay informed by retrieving the latest content from the sites they are interested in. It saves time by not needing to visit each site individually. It also ensures the privacy of the users by not needing to join the site's email newsletter. The number of sites offering RSS feeds is growing rapidly and includes big names like Microsoft and Asp.Net websites.

Useful links for CSS

I'll add more to the list when I've found more information here.

1. Internet Explorer & CSS issues

2. Ten ways to speed up the download time of your web pages (some key points here, a must read article.)

3. Ten CSS tricks you may not know (There are some tricks here that you shouldn't miss too)

4. CSS Help Pile - A huge pile of CSS-related tips, tricks & resources.

5. 53 CSS-Techniques You Couldn't Live Without (Here, you can learn the specific technique that you want to use in your web site. Another Must Read article.)

6. Layout Gala: a collection of 40 CSS layouts - Here you'll get some reference CSS layout sites.

7. MaxDesign - Sample CSS Page Layouts (with step by step layout tutorial too)

8. CSSplay - There are some demos, menus, layouts, boxes examples.

Create Table using storeprocedure

Here is an example:

Create Proc [dbo].[TestStoreProcedure]


Create Table [dbo].[TestTable]


[JournalVoucherNo] int NOT NULL Primary key identity(1,1),

[Description] nvarchar(max),

[Date] datetime,

[Cost] money,

[Role] char(4),

[IsAdmin] bit

[CreatedBy] int

[UpdatedBy] int



* using [dbo] for including new features of 2005 and we can give another name(eg..AP,AR,GL,Budget)that we can define like that schema which make more efficient for database features.

* using brackets [] to embrace the table name or field name so that even reserved words have been used, the names are still allowed.

* the field name [Id] has been defined to be primary key and it's auto increment by 1, start from 1. (Null is not allowed for this column)

* the data type for boolean is "bit" here.

* the difference between using "char" & "varchar" is that, when you define the size for char, no matter how many characters have been stored, it'll use up all the space defined. But for "varchar", it'll allocate just the size enough to store the variables. For variable string, it's good to use "varchar" as the data type.

* The maximum size for varchar is 8000 characters.

Fill up Leading Zero(s) In JavaScript

When the user didn't input in the max length in the text box, leading zero(s) will
automatically be added.For example:Month Calculation : (123456789).If the user only selected "1", it hasn't reached the max length (01) yet, then a leading zero will be added to become "01"

function AddLeadingZero(currentField)

//Check if the value length hasn't reach its max length yet

if (currentField.value.length != currentField.maxLength)

//Add leading zero(s) in front of the value

var numToAdd = currentField.maxLength - currentField.value.length;
var value ="";
for (var i = 0; i < numToAdd;i++)
value += "0";
currentField.value = value + currentField.value;

Copy this function in the code file:
public static void AddLeadingZeroAttribute(TextBox txt)

//Add leading zero when focus is lost
txt.Attributes.Add("OnBlur", "AddLeadingZero(this)");


"OnBlur" event will be triggered when the textbox loses the focus. Whenever the user finished keying in values and left the textbox, the AddLeadingZero() function will be called.

Show message box by server side

private void ShowMessageBox(string Message)
Label lblMessageBox = new Label();
lblMessageBox.Text =
"#script language='javascript'#" + Environment.NewLine +
"window.alert('" + Message + "')#/script#";Page.Controls.Add(lblMessageBox);

To call the message box function and just pass message value :

ShowMessageBox("Cannot Delete!");

Differences between Cache, Session and ViewState


  • memory.
  • allow you to store difficult and complex constructed data which will can be reused.
  • is available to be accessed from global/application level where one reference to memory is updated. Each request will use the same cache for different users.


  • a period of time that is shared between the web application and the user.
  • Each user that is using the web application has their own session.
  • The Session variables will be cleared by the application which can clear it, as well as through the timeout property in the web config file.
  • Session variables will use different session variables for each different user.


  • hidden data that is kept by ASP.NET pages.
  • track the changes to a web site during post backs.
  • All server controls contain a view state. [EnableViewState property - enable/disable if the control properties will be held in hidden fields.]
  • Having a large ViewState will cause a page to download slowly from the users side.- When a user clicks on a button and a post back occurs, all the view state information has to be posted back to the server which causes a slower request.
  • ViewState should be limited to what is needed.- Data can also be written into the ViewState. - The ViewState only persists for the life cycle of the page.
  • If the page redirects to another page, or even to itself, the ViewState will be reset.
  • ViewState should be used to hold small amonts of data, which will be only used on the current page

Split String

The IC Number format is "770131-08-1234", and I need to split the text into 3 different sections, to display on the screen.

There are many times we need to split a string with a delimiter.The Split() function can help to deal with these cases easily.Note that the delimiter is a character.

Example 1:
Split with one delimiterstring stringToSplit = "770131-08-1234";
string[] splitStrings = stringToSplit.Split('-');
splitStrings[0] will be "770131".
splitStrings[1] will be "08".
splitStrings[2] will be "1234".

Example 2:
Split with more than one delimiterstring stringToSplit = "770131;08-1234";
string[] splitStrings = stringToSplit.Split('-',';');
splitStrings[0] will be "770131".
splitStrings[1] will be "08".
splitStrings[2] will be "1234".

Example 3:
Split without delimiterSpaces will be treated as delimiter.
string stringToSplit = "770131 08 1234";
string[] splitStrings = stringToSplit.Split();
splitStrings[0] will be "770131".
splitStrings[1] will be "08".
splitStrings[2] will be "1234".

Master-Detail with the GridView, DetailsView and ModalPopup Controls

A while back I wrote a post describing how the DetailsView, GridView, UpdatePanel and the AjaxControlToolkit's ModalPopup controls could be used to implement the common Master/Details UI pattern. I cheated a bit when creating my original example in that I didn't really complete the implementation - the Save button on the popup didn't actually do anything. Since writing that post I have received a lot of email and a number of people left comments asking me to complete the example - so here it is. If you plan on reading through this article, I recommend playing around with the demo site to get a feel for how the page works. All data changes are only persisted to memory, so don't worry about messing up the data set.


I am sure everyone is pretty familiar with Master/Details style of editing data, but just in case - here is how my page works. The grid shows 12 rows of customer data. The far right column in the grid contains a hyperlink that when clicked brings the detail view of the row into focus so the corresponding row can be edited. The detail view is a popup control and contains a Save and Close buttons. When close is clicked, the detail popup is dismissed and the user goes back to viewing the main grid. When they click Save, some simple validation checks are run (all are RequiredFieldValidators for this sample) and the new data values are persisted, and finally the detail popup is dismissed and the main grid is refreshed so that it displays the changes.

Customer GridView

The Customer Grid is just a regular GridView. I have used BoundFields to bind to the data and I am using a TemplateField for rendering the 'Edit' anchor.

When 'Edit' is clicked, I want to show the detail view popup. To accomplish this I set the CommandName of the 'Edit' button to Select - this will cause the SelectedIndexChanged event to fire on the server. Inside this event handler, I force the DetailView to databind, passing the datasource it is bound to the ID that corresponds to the row the user clicked. Finally, I let the UpdatePanel the DetailView is contained in that it needs to update its contents and invoke the Show server side method of my ModalPopupExtender which will cause the popup to be displayed when the partial page is reloaded on the client.

Here are the 2 events handlers that I am using to accomplish this bit of work. The top event handler fires when 'Edit' is clicked and the explicit call to DataBind forces the DetailView's corresponding ObjectDataSource's Selecting event to fire. In this handler I use the SelectedIndex of the GridView to fetch the ID the data source needs.

Customer DetailsView

The DetailsView for the individual customer records is also pretty simple - except because I have included RequiredFieldValidators I wasn't able to use the BoundFields and instead I had to explicitly define the EditItemTemplate for each of the fields.

Just below the DetailsView, I have 2 buttons that interact with the ModalPopupExtender. The Close button dismissed the popup without posting back or committing any changes. The Save button does post back, moves the data out of the DetailsView and back to the ObjectDataSource, hides the ModalPopupExtender and finally causes the main GridView to refresh so it displays the changes.

Here is the logic I have wired to the Save button's click handler

Apply a Yellow Fade to the Updated Row in the GridView

And while this has been pretty much nuts and bolds functionality thus far, I couldn't resist trying to spice it up by applying a yellow fade to the row in the main grid that was updated. To implement this feature, I needed a way to send a bit of information back from the server that let me know what row in the grid was updated. So my approach was to use the ScriptManager's RegisterDataItem method to accomplish this. Here is the doc from MSDN:

Sends custom data to a control during partial-page rendering, and indicates whether the data is in JavaScript Object Notation (JSON) format.

Just what I need - so after the Save button is clicked, back in the server side event handler, I call RegisterDataItem and pass the index of the updated row to the GridView. Then after the partial refresh has occurred back on the client, I extract the row index from the DataItem's collection, use it to find the row that changed and give it a custom CSS class.
So I added the following call to my Save button handler to register the index of the row that was changed.

And then added the following JavaScript to my page to track down the corresponding TR element in the rendered table and apply the updated CSS class to the row.

And like magic I get a yellow background applied to the row that was edited. The background color stays in place for 1.5 seconds then my timeout handler fires and removes it. A poor man's animation, but the plumbing is in place for me to improve upon. Below are the screen shots of how it looks.