How to do a Partial PostBack in Asp.Net using UpdatePanel and ScriptManager

← PrevNext →

Asynchronous Java and XML also known as the AJAX has come a long way. Ajax makes server callback easy and does it without refreshing the entire page. It has proved its usefulness. Moreover, it has made web browsing easy and thrilling.

Here in this article I am going to show you how to do a partial postback using an UpdatePanel and ScriptManager controls.

Partial PostBack or Partial Page Rendering of a Web page can be done using Microsoft’s two Ajax controls. The UpdatePanel control and the ScriptManager control. These are server side controls and it helps us doing a PostBack without refreshing the entire web page.

A PostBack is generally calling the server to execute a specific request, like getting data from a database table.

PostBack Using UpdatePanel

Add ScriptManager and UpdatePanel Control

Start Visual Studio and create a New Web Site. In the Design Mode click the Toolbox and look for AJAX extensions. From the list of extensions, drag and drop the ScriptManager control, followed by the UpdatePanel control on your web page.

<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            ...
        </asp:UpdatePanel>
    </div>
</form>

We need a DropDownList control for our demo. The drop down will have a list of Employee names. Selecting a name from list will do a PostBack to the server and fetch more details about the employee from an SQL Server table.

Create a Table in SQL Server

For the demo, you can use the Employee Details table, which I have created before. It’s ideal for our example here.

The Markup
<!DOCTYPE>
<html>
<head>
    <title>AutoPostBack using UpdatePanel</title>
    <style>
        .ddl { 
            font:15px Arial;
            font-weight:normal; 
            color:#000; 
            height:20px; 
            margin-bottom:1px; 
            border:solid 1px #CCC; 
            border-radius:2px; -moz-border-radius:2px; -webkit-border-radius:2px; 
            padding:1px; 
            width:120px;
        }
        #divDetails { 
            float:right; 
            position:absolute; 
            left:150px; 
            top:13px; 
            background:#F7F7F9;
            border:solid 1px #D6DBE1;
            color:#333; 
            padding:5px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">

    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:DropDownList ID="DropDownList1"
                        runat="server"
                        AutoPostBack="true" 
                        OnTextChanged="ShowEmpDetails"
                        CssClass="ddl">
                            
                        <asp:ListItem></asp:ListItem>
                        <asp:ListItem>CHIN YEN</asp:ListItem>
                        <asp:ListItem>MIKE PEARL</asp:ListItem>
                        <asp:ListItem>GREEN FIELD</asp:ListItem>
                        <asp:ListItem>DEWANE PAUL</asp:ListItem>
                        <asp:ListItem>MATTS</asp:ListItem>
                        <asp:ListItem>PLANK OTO</asp:ListItem>
                    </asp:DropDownList>

                    <div id="divDetails" runat="server"></div>
                </ContentTemplate>

                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="DropDownList1" />
                </Triggers>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>
Code Behind (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection myConn = default(SqlConnection);
    SqlCommand sqComm = default(SqlCommand);

    protected void Page_Load(object sender, EventArgs e)
    {
        setConn();
    }

    // FETCH DATA FROM "EMPLOYEE DETAILS" TABLE.
    protected void ShowEmpDetails(object sender, EventArgs e)
    {
        string sQuery = "SELECT EmpID, Mobile, Email FROM EmployeeDetails WHERE EmpName = '" + 
            DropDownList1.Text + "'";
        SqlDataReader sdrEmp = GetDataReader(sQuery);
        try
        {
            if (sdrEmp.HasRows)
            {
                String sDetails = System.String.Empty;
                if (sdrEmp.Read()){
                    sDetails = "ID: " + sdrEmp["EmpID"] + "<br />";
                    sDetails = sDetails + "Name: " + DropDownList1.Text + "<br />";
                    sDetails = sDetails + "Mobile: " + sdrEmp["Mobile"] + "<br />";
                    sDetails = sDetails + "Email ID: " + sdrEmp["Email"];
                }
                divDetails.InnerHtml = sDetails;
            }
        }
        catch (Exception ex) { }
        finally
        {
            sdrEmp.Close();
            sdrEmp = null;
        }
    }

    private bool setConn()
    {
        // SET DATABASE CONNECTION.
        try
        {
            myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DNA_DB"].ConnectionString);
            myConn.Open();

            sqComm = new SqlCommand();
            sqComm.Connection = myConn;
        }
        catch (Exception ex) { return false; }
        return true;
    }

    private SqlDataReader GetDataReader(string sQuery)
    {
        SqlDataReader functionReturnValue = default(SqlDataReader);
        sqComm.CommandText = sQuery;
        sqComm.ExecuteNonQuery();
        functionReturnValue = sqComm.ExecuteReader();
        sqComm.Dispose();
        return functionReturnValue;
    }
}
VB.Net
Option Explicit On
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Dim myConn As SqlConnection
    Dim sqComm As SqlCommand

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        setConn()
    End Sub

    ' FETCH DATA FROM "EMPLOYEE DETAILS" TABLE.
    Protected Sub ShowEmpDetails(ByVal sender As Object, ByVal args As EventArgs)
        Dim sQuery As String = "SELECT EmpID, Mobile, Email FROM EmployeeDetails " & _
            "WHERE EmpName = '" & Trim(DropDownList1.Text) & "'"
        Dim sdrEmp As SqlDataReader = GetDataReader(sQuery)
        Try
            Dim sDetails As String = ""
            If sdrEmp.Read Then
                sDetails = "ID: " & sdrEmp.Item("EmpID") & "<br />"
                sDetails = sDetails & "Name: " & Trim(DropDownList1.Text) & "<br />"
                sDetails = sDetails & "Mobile: " & sdrEmp.Item("Mobile") & "<br />"
                sDetails = sDetails & "Email ID: " & sdrEmp.Item("Email")
            End If
            divDetails.InnerHtml = sDetails
        Catch ex As Exception
        Finally
            sdrEmp.Close() : sdrEmp = Nothing
        End Try
    End Sub

    Private Function setConn() As Boolean
        ' SET DATABASE CONNECTION.
        Try
            myConn = New SqlConnection("Data Source=DNA;Persist Security Info=False;" & _
                "Integrated Security=SSPI;
                "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;")

            myConn.Open()

            sqComm = New SqlCommand
            sqComm.Connection = myConn
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function

    Private Function GetDataReader(Optional ByVal sQuery As String = "") As SqlDataReader
        sqComm.CommandText = sQuery
        sqComm.ExecuteNonQuery()
        GetDataReader = sqComm.ExecuteReader
        sqComm.Dispose()
    End Function
End Class

Note: Add a connection string in the Web.Config file inside the <configuration> tag. The Web.Config file will automatically created when you create a New Web Site using the Visual Studio.

<connectionStrings>
    <add name="DNA_DB" connectionString="Data Source=DNA;Persist Security Info=False;
        Integrated Security=SSPI; Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=dna; 
            Connect Timeout=30;"/>
</connectionStrings>

That's it. Thanks for reading.

← PreviousNext →