Click here to Skip to main content
Click here to Skip to main content
Go to top

Triggering AJAX UpdatePanel from a Button Click or DropDownList Selection Change in Code-Behind

, 28 Apr 2008
Rate this:
Please Sign up or sign in to vote.
This article shows how to make a Button click or DropDownList selection change trigger an update to an AJAX UpdatePanel with all code written in code-behind

Introduction

This is one of those problems that isn't technically difficult, like writing a word processing program, but rather is just a matter of finding the right code sequence to make it work. Much of the AJAX documentation shows how to use the controls placed in HTML markup. However, there are some situations where the programmer would prefer to add controls to a page dynamically from the code-behind (see my article Building ASP.NET Web Pages Dynamically in the Code-Behind). Using AJAX controls in this manner is not well documented. In looking for the answer, I found that other developers were posting to AJAX message boards with the same problem - particularly for the DropDownList. So here I present the solution. If you are having the same problem, I hope this is the first place you looked.

DropDownList Selection Change Sample Code

This simple example shows how to trigger an UpdatePanel update when a DropDownList selection changes. The HTML markup is just as it appears by default in Visual Studio, but with the addition of a PlaceHolder control to hold the UpdatePanel and the link to the ScriptManager required for AJAX.

<%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="DropDown.aspx.cs" Inherits="AjaxTest_DropDown" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <div>
    <asp:PlaceHolder id="LocalPlaceHolder" runat="server"></asp:PlaceHolder>

    </div>
    </form>
</body>
</html>

Below, you see the code-behind file for the page. I create the UpdatePanel and add it to the placeholder. I add a Label control to the UpdatePanel. When the DropDownList selection changes, the Label displays the current time. Some important points to consider:

  1. Note that both the Label and the DropDownList are added to the UpdatePanel - not to the PlaceHolder.
  2. Be sure to set the DropDownList.AutoPostback to true.
  3. Be sure to create a trigger for the event and add it to the UpdatePanel with the control ID of the DropDownList.
  4. Pay attention to the names of the event and controls. Mistyping a name will mean the page won't work. This code is easy, but it is not forgiving. Even a minor mistake will mean that the panel does not update.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AjaxTest_DropDown : System.Web.UI.Page
{
    protected Label m_TimeLabel;

    protected void Page_Load(object sender, EventArgs e)
    {
        // create an update panel
        UpdatePanel updatepanel = new UpdatePanel();

        // add the update panel to the placeholder
        LocalPlaceHolder.Controls.Add(updatepanel);

        // create a label to show time
        m_TimeLabel = new Label();
        m_TimeLabel.Text = DateTime.Now.ToString();

        // add the label to the update panel
        updatepanel.ContentTemplateContainer.Controls.Add(m_TimeLabel);

        // create a drop down list
        DropDownList dropdown = new DropDownList();
        dropdown.ID = "Dropdown1";
        dropdown.AutoPostBack = true; // this is absolutely required
        dropdown.Items.Add("Item 1");
        dropdown.Items.Add("Item 2");
        dropdown.Items.Add("Item 3");
        dropdown.Items.Add("Item 4");

        // add the drop down list to the update panel
        updatepanel.ContentTemplateContainer.Controls.Add(dropdown);

        // create a trigger
        AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();

        // associate the trigger with the drop down
        trigger.ControlID = "Dropdown1";
        trigger.EventName = "SelectedIndexChanged";

        // add the trigger to the update panel
        updatepanel.Triggers.Add(trigger);
    }

    protected void Dropdown1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // event to handle drop down change
        m_TimeLabel.Text = DateTime.Now.ToString();
    }

}

Below, you see a screen shot of this simple Web page.

Triggering the Update from a Button

You can also trigger the update from a Button control. This code shows how. While the markup for the page would be the same, pay attention to the differences from the DropDownList. Note how specifying the event handler for the Button is different than for the DropDownList.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AjaxTest_ButtonUpdate : System.Web.UI.Page
{
    protected Label m_TimeLabel;

    protected void Page_Load(object sender, EventArgs e)
    {
        // create an update panel
        UpdatePanel updatepanel = new UpdatePanel();

        // add the update panel to the placeholder
        LocalPlaceHolder.Controls.Add(updatepanel);

        // create a label to show time
        m_TimeLabel = new Label();
        m_TimeLabel.Text = "Initial Text";

        // add the label to the update panel
        updatepanel.ContentTemplateContainer.Controls.Add(m_TimeLabel);

        // create a drop down list
        Button button = new Button();
        button.ID = "Button1";
        button.Text = "Update";
        button.Click += new EventHandler(Button1_Click);

        // add the button to the update panel
        updatepanel.ContentTemplateContainer.Controls.Add(button);

        // create a trigger
        AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();

        // associate the trigger with the drop down
        trigger.ControlID = "Button1";
        trigger.EventName = "Click";

        // add the trigger to the update panel
        updatepanel.Triggers.Add(trigger);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        // event to handle drop down change
        m_TimeLabel.Text = DateTime.Now.ToString();
    }
}

Conclusion

That is all there is to it. Although a bit difficult to figure out initially, it is simple to implement once you know what to do.

History

  • 28th April, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Robert Pittenger, MCPD-EAD
President Starpoint Software Inc.
United States United States
Bob Pittenger is founder and President of Starpoint Software Inc. He holds a B.A. degree from Miami University, M.S. and Ph.D. degrees from Purdue University, and an MBA from Xavier University. He has been programming since 1993, starting with Windows application development in C++/MFC and moving to C# and .NET around 2005 and is a .NET Microsoft Certified Professional Developer.
 
Bob is the author of two books:
Billionaire: How the Ultra-Rich Built Their Fortunes Through Good and Evil and What You Can Learn from Them
and
Wealthonomics: The Most Important Economic and Financial Concepts that Can Make You Rich Fast.
Visit http://www.billionairebook.net for more information.

Comments and Discussions

 
GeneralMy vote of 2 Pinmembershek12430-Nov-11 1:55 
GeneralAmazing! Pinmemberstevenode13-Mar-11 9:03 
GeneralMy vote of 1 Pinmemberid-xtrax3-Sep-09 3:45 
Generalhi Pinmemberatefeh mokhtary31-Aug-08 1:03 
QuestionTrigger when left the drowdownbox PinmemberJeroenh26-May-08 20:22 
GeneralSelectedIndexChanged is not called Pinmemberthiru_thiru3-May-08 11:19 
GeneralRe: SelectedIndexChanged is not called PinmemberRobert Pittenger17-May-08 11:41 
GeneralAdd handler is missing...Please check Pinmembersrinath g nath1-May-08 4:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 28 Apr 2008
Article Copyright 2008 by Robert Pittenger, MCPD-EAD
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid