Wednesday, December 21, 2011

Prevent postback events on page refresh

A common concern of ASP.NET developers is, "How do I prevent previously submitted form data from being reinserted into the database when the user presses the browser's Refresh button?"

Different solutions are available for this problem.

  1. Reload the page after successful postback

    A simple solution is to Reload the same page using Response.Redirect after successful transaction.

    Response.Redirect(Request.Url.ToString(), false);

    A disadvantage of this approach is that page ViewSate will not be retained.

  2. Using OnClientClick event (javascript)

    Create a javascript function which validates the fields to be submitted. If any validation failed it has to return false otherwise it has to return true.

    To avoid the post back handle the OnClientClick event call the javascript function which retuns true on successful validation otherwise false. If OnClientClick gets true from the script function then it would raise the OnClick event, otherwise it would not.

    <asp:Button ID="btnValidate" runat="server" Text="Click Here!!" OnClientClick=" return ValidateEmail()" OnClick ="btnValidate_Click"/>

    Below is the sample javascript:

    function ValidateEmail()
    var x = document.getElementById('txtemail');

    var val = x.value;
    if(val == "")
    alert("Please enter your email id");
    return false;
    return true;

    The fields should be cleared on successful completion of postback.

  3. Server-side code using Session and ViewState variables

    A simple way to implement refresh trapping is by the use of a date/time stamp held in a ViewState variable and a date/time stamp held in the user's Session. When the page is first loaded, a Session variable is populated with the current date/time. On the page's PreRender event, a ViewState variable is set to the value of the Session variable. These two values are compared to each other immediately before the database INSERT command is run.

    If they are equal, then the command is permitted to execute and the Session variable is updated with the current date/time, otherwise the command is bypassed. Should the user refresh the page, the ViewState variable will be repopulated from the post header, so then the ViewState and Session variables will no longer hold the same values, and the INSERT command will not run. Note that ViewState needs to be enabled on the page for this to work; if ViewState is not enabled then a hidden form field may be used instead.

    public void Page_Load(object sender, EventArgs e)
    if (!Page.IsPostBack) {
    Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());

    public void Page_PreRender(object sender, EventArgs e)
    ViewState["update"] = Session["update"];

    public void Button1_Click(object sender, EventArgs e)
    if (Session["update"].ToString() == ViewState["update"].ToString()) {
    if (AddEmployee(firstName.Text, lastName.Text) == 0) {
    Message.Text = "Success";
    Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
    } else {
    Message.Text = "Failure";
    } else {
    Message.Text = "Failure - Session";
    firstName.Text = "";
    lastName.Text = "";

Happy coding…

Saturday, October 22, 2011

Child window (popup) close event in parent window

This is the most useful and most wanted code for raising window close event of child window from parent window.

<script type="text/javascript">
   var childWindow = null;
   var timer;
   var flag = 1;
   function openChildWindow() {
       childWindow ='child.htm', 'My popup', 'width=400,height=250');
   function checkChildWindowStatus() {
       if (childWindow.closed) {
           if (flag == 1)
                flag = 0;
           else {
                timer = 0;
                flag = 1;
   window.onload = function () {
       timer = setInterval('checkChildWindowStatus()', 1000);

In the above code childWindow is the variable which reference to the popup window. Using this window status can be identified.

checkChildWindowStatus() is the function where the popup window status is checking and based on this some action (page refresh) can be performed in parent window. This function is getting called for frequent interval of time using serInterval() method.

Happy coding…

InitCap in

Below is the line of code for rendering text in InitCap format.


Here the source string should be in lower case.

Happy coding…

Saturday, October 8, 2011

Access web control on Nested master page from content page

For example I have a DropDownList control in the inner master page. This control can be accessed from the content page in 2 ways.

  1. Using the findcontrol method to access the DropDownList, you need to use the DropDownList's ClientID.

    For example :

    DropDownList list = (DropDownList)this.Master.FindControl("ctl00$ctl00$ContentPlaceHolder1$DropDownList1");

  2. Expose the DropDownList control in the inner master page's code bhind, then the control can accessed directly.
    • Expose the DropDownList control:

        public DropDownList list
                    return this.DropDownList1;


  • Add the masterType for the content page to strong type the master page:

    <%@ MasterType VirtualPath="~/Masterpage/NestMasterPage/MasterPage2.master" %>


  • Access the DropDownList in the content page's codebehind:

            DropDownList list = this.Master.list;

Happy Coding…

Wednesday, August 17, 2011

IDENT_CURRENT–Retrieve last inserted identity of record


It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

Happy Coding…

Tuesday, June 7, 2011

Simulating ListView’s ItemCommand Event

Data controls in like GridView, DataList, Repeater, ListView,… are having an event called ItemCommand.

This event will raise whenever any button, linkbutton,… are clicked.

But my requirement is to call the ItemCommand event whenever the ListView.Databind() is done.

Below is the procedure I followed for that.

System.Web.UI.WebControls.LinkButton lnkbtn = (System.Web.UI.WebControls.LinkButton)lvMyAlbums.Items[0].FindControl("lnkAlbum");

            ListViewCommandEventArgs ev = new ListViewCommandEventArgs(lvMyAlbums.Items[0], lnkbtn, new CommandEventArgs(lnkbtn.CommandName, lnkbtn.CommandArgument));

            // Call ItemCommand handler

            lvMyAlbums_OnItemCommand(lvMyAlbums, ev);


Happy coding…

Wednesday, June 1, 2011

Convert DateTime to Indian Standard Time format in SQL Server

DATEADD() function would be used to convert UTC to IST in SQL Server.

Below is the sample code for that.


Happy Coding…

Thursday, May 26, 2011

URL shortener in .net using API

It’s simple to generate shorten url based on long url using API.

For this we need to have account with which is free. After sign up completed, you will be provided with an API key

This API key can be used to access the API. Below is the code for API class in c#

public static class BitlyApi
private const string apiKey = "[add api key here]"
private const string login = "[add login name here]"

public static BitlyResults ShortenUrl(string
var url =
HttpUtility.UrlEncode(longUrl), login, apiKey);
var resultXml = XDocument.Load(url);
var x = (from result
in resultXml.Descendants("nodeKeyVal"
UserHash = result.Element(
ShortUrl = result.Element(

public class
public string
UserHash { get; set; }

public string ShortUrl { get; set; }

Now, we can generate short url as below:

string strShortUrl = BitlyApi.ShortenUrl(“<long url>).ShortUrl;

Happy Coding…

Monday, May 23, 2011

Customizing Date format in WPF

The datepicker control in WPF allow short and Long formats. By default it will take system date format.

So we can change the date format as our application requires like dd/MM/yyyy or MM/dd/YYYY,…

Need to write some couple of lines under Application_Startup Event in App.XAML.

Below is the code for custom date format.

Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();

Thread.CurrentThread.CurrentCulture.DateTimeFormat.DateSeparator = "/";

Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";


This is event should be initiated from XAML code like below.


Happy Coding…