Wednesday, 31 December 2014

Difference between document.ready and pageLoad

 Difference between document.ready and  pageLoad:
We think pageLoad() and jQuery’s $(document).ready() events do the same. Both methods seem too similar in simple demo example. But $(document).ready() and pageLoad() methods are very much differ in functioning.In this article, I will explain the major differences between $(document).ready() and pageLoad() methods.
Introducing $(document).ready()
JQuery’s document.ready() method gets called as soon as DOM is ready (means browser has parsed the HTML and built the DOM tree). It is cross browser compatible means behave equally on all browsers. If your web page has large images, it will not wait for loading of images completely. Hence it may called before pageLoad() method. We can have multiple document.ready() methods on a web page that will be called in coming sequence.

    <script type="text/javascript">
    $(document).ready(function(){
    // Gets called as soon as DOM is ready
    //code here
    });
    </script>

Introducing pageLoad()

pageLoad() method gets called when images and all associated resources of the page have been fully loaded. Suppose your web page has large size images then until all the images are not fully loaded on the page, pageLoad() method will not called. pageLoad() method is not browser compatible. We can have only one pageLoad() method on a web page.

    <script type="text/javascript">
    function pageLoad()
    {
    // gets called when page have been fully loaded
    //code here
    }
    </script>

Introducing Update Panel Partial PostBack with pageLoad() and $(document).ready()

Since we know, in asp.net update panel gets partially postback to the server. Hence If you are using $(document).ready() and pageLoad() methods on the page, it is mandatory to know the difference between both the methods.

pageLoad() methods is called each and every partial postback of update panel but $(document).ready() is not called each and every partial postback of update panel. $(document).ready() is called only one time (during first time of page loading). Hence code written in $(document).ready() method will not be initialized each and every partial postback.

    <script type="text/javascript">
    function pageLoad()
    {
    // code for initialization in each and every partial postback
    }
    $(document).ready(function(){
    // code for one time initialization
    });
    </script>
    <asp:ScriptManager ID="ScriptManger1" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <!-- Asp.net Controls Here -->
    </ContentTemplate>
    </asp:UpdatePanel>

An ASP.NET AJAX alternative to $(document).ready()

If you are using AJAX on your asp.net web page then you can use Application.add_init() method in place of $(document).ready() for one time initialization.

    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <script type="text/javascript">
    Sys.Application.add_init(function() {
    // Initialization code here, meant to run once.
    });
    </script>

Note that to call Application.add_init, we need to place it after the ScriptManager. This is required because the ScriptManager injects its reference to MicrosoftAjax.js at that location. Attempting to reference the Sys object before Script Maanager will throw a javascript error "sys is undefined"
Note

    $(document).ready()

        Best for onetime initialization.

        Called as soon as DOM is ready; may called slightly before than pageLoad().

        Cross browser compatible.

        Unable to re-attach the functionality to elements/controls of the page affected by partial postbacks.
    pageLoad()
        Not best for onetime initialization if used with UpdatePanel.

        Not Cross browser compatible.

        Best to re-attach the functionality to elements/controls of the page affected by partial postbacks with UpdatePanel.
    Application.Init()
        Useful for one time initialization if only ASP.NET AJAX is available.

        More work required to wire the event up.

        "sys is undefined" javascript error may occurs if you are not careful.

Monday, 29 December 2014

How to call asp.net page methods from JSON

 How to call asp.net page methods from JSON

Here I will explain how to use JQuery and JSON to call asp.net page methods.

 If we want to call our page methods with JQuery then we need to use JQuery.ajax method and our JQuery declaration will be like this

$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "default.aspx/test",
data: "{}",
dataType: "json",
success: function(data) {
//Write functionality to display data
},
error: function(result) {
alert("Error");
}
});
This is the function declaration of JSON format we are using this JSON function to call web methods using JQuery $.ajax() whenever we need to make Ajax call with JQuery then we will use JSON functions like as we mentioned in above format. Here type, ContentType and dataType are same for all functions only url, data and success and error parameters will vary based on our requirement.

url: This is the path of our Webmethods

data: we will pass parameters using this parameter if no parameters then we need to use data: "{}"

success: Once our web method execution completed then success function will execute and return required data
error: This parameter is used to display required error message whenever we get problem.

(Note: JSON is a case sensitive please be careful before write JSON format of data)
Now create new website and write the following code in your aspx page

 <html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>JQuery Call asp.net page methods</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "default.aspx/DisplayData",
data: "{}",
dataType: "json",
success: function(data) {
$("#lbltxt").text(data.d);
},
error: function(result) {
alert("Error");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<label id="lbltxt" runat="server"></label>
</form>
</body>
</html>

 If you observe above code in header section I added script file link by using that file we have a chance to interact with JQuery.

Now open code behind file and add the following namespaces


using System;
using System.Web.Services;
After that write the following code

C#.NET Code


protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string DisplayData()
{
return DateTime.Now.ToString("dd/MM/yyyy");
}

Tuesday, 23 December 2014

What is Lvalues and Rvalues in C#

What is  Lvalues and Rvalues in C#:

There are two kinds of expressions in C#:

    lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.

    rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:

int g = 10;

But following is not a valid statement and would generate compile-time error:

10 = 100;

Tuesday, 16 December 2014

Session is not applicable in Windows Application

Session is not applicable in Windows Application :
Session or ViewState is not applicable in Windows Application. We are using Session in Web
Application becuase http is a stateless protocol and we need to maintain state of the application
using any of the state management technology available like session, query string. These state
management technologies are not available for Windows Application.

In Windows Form, if you want to share a object in different forms, you may use global objects.

Use a global class file to get and set the values of an object

Create a class Class1.cs and add the following code:
class Class1
    {
        static String str = "";
        public static String GetData()
        {
            return str;
        }

        public static void SetData(String str1)
        {
            str = str1;
        }
    }

Now Create two Form.
In First Form take one TextBox and One Button
Add the following code in Button Click Event:
 private void button1_Click(object sender, EventArgs e)
        {
            Class1.SetData(textBox1.Text.Trim());

            Form2 f = new Form2();
            f.Show();
        }

In Second Form take one Label
Write the following code in Form Load event of Form2:
 private void Form2_Load(object sender, EventArgs e)
        {
            label1.Text = Class1.GetData();
        }
*** Happy Coding***

Wednesday, 3 December 2014

Combining Two DataTable in VB.Net

Combining Two DataTable in VB.Net:

In VB.NET or C#  we  can merge two DataTable using Table1.merge(Table2).
Merging DataTable is an easy task.  When wh megre two table then content of second table will append after content of first table.

If we want to combine content of two DataTable side by side ,this is not an easy task.
But if we want to combining two DataTable then add the following code:

Public Function CombineTable(_dtGridDetails As DataTable, _dtSubGridDetails As DataTable) As DataTable
        'first create the datatable columns
        Dim mydataSet As New DataSet()
        mydataSet.Tables.Add("  ")
        Dim myDataTable As DataTable = mydataSet.Tables(0)

        'add left table columns
        Dim dcLeftTableColumns As DataColumn() = New DataColumn(_dtGridDetails.Columns.Count - 1) {}
        _dtGridDetails.Columns.CopyTo(dcLeftTableColumns, 0)

        For Each LeftTableColumn As DataColumn In dcLeftTableColumns
            If Not myDataTable.Columns.Contains(LeftTableColumn.ToString()) Then
                myDataTable.Columns.Add(LeftTableColumn.ToString())
            End If
        Next

        'now add right table columns
        Dim dcRightTableColumns As DataColumn() = New DataColumn(_dtSubGridDetails.Columns.Count - 1) {}
        _dtSubGridDetails.Columns.CopyTo(dcRightTableColumns, 0)

        For Each RightTableColumn As DataColumn In dcRightTableColumns
            If Not myDataTable.Columns.Contains(RightTableColumn.ToString()) Then
                ' if (RightTableColumn.ToString() != RightPrimaryColumn)
                myDataTable.Columns.Add(RightTableColumn.ToString())
            End If
        Next

        'add left-table data to mytable
        For Each LeftTableDataRows As DataRow In _dtGridDetails.Rows
            myDataTable.ImportRow(LeftTableDataRows)
        Next

        For nIndex As Integer = 0 To myDataTable.Rows.Count - 1
            If nIndex = _dtSubGridDetails.Rows.Count Then
                Exit For
            End If
            myDataTable.Rows(nIndex)(2) = _dtSubGridDetails.Rows(nIndex)(1)
        Next
        Return myDataTable
    End Function

------------
Happy Coding.