posts - 216, comments - 177, trackbacks - 68

My Links

News




I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net) and born in Bangladesh.
I work for Ocean Informatics Pty Ltd as a Senior Developer - Analyst.
I am also co-founder and core developer of Pageflakes www.pageflakes.com
and most recently created SmartCodeGenerator

My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET
Smart Code Generator .NET: Usage Overview
Smart Code Generator .NET: Architectural Overview
Smart Code Generator .NET: using with NAnt and Cassini

Archives

Free Programming Language Training

Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

Here is a cool technique on how to identify which control has triggered the UpdatePanel (when dynamic controls are added during runtime). Here we will use the Request Object to identify this.

Lets say we have updatePanel1

<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional">
  <ContentTemplate>
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <asp:Panel ID="Panel1" runat="server" Height="50px" Width="125px">
    </asp:Panel>
  </ContentTemplate>
</asp:UpdatePanel>
</div>


and during runtime we go and add dynamic buttons.... button1, button2 in the Panel1....

LinkButton button1 = new LinkButton();
button1.ID = "button1"
button1.Text = "button1"

LinkButton button2 = new LinkButton();
button2.ID = "button2"
button2.Text = "button2"

Panel1.Controls.Add(button1);
Panel1.Controls.Add(button2);


now we can identify which button is clicked, by looking at the Request Object and passing the key of the ScriptManager.ID:

protected override void CreateChildControls()
{
  base.CreateChildControls();
  if( ScriptManager1.IsInAsyncPostBack )
  {
    string fromWhere = Request[ScriptManager1.ID];
    Label1.Text = fromWhere;
  }
}

 

This will get the following wtring:
On Button1 click: UpdatePanel1|button1
On Button2 click: UpdatePanel1|button2

if we look carefully at the string  "UpdatePanel1|button1" we see that it has 2 parts, the ID of the UpdatePanel which got triggered and the ID of the control (ie. button1) which triggered the event.

So we can do something like this.....

protected override void CreateChildControls()
{
  base.CreateChildControls();
  if( ScriptManager1.IsInAsyncPostBack )
  {
    string fromWhere = Request[ScriptManager1.ID];   

    if( fromWhere.Contains("button1") )
    {
        //Do something here
    }
    else if (fromWhere.Contains("button2")
    {

        //Do something else....as you wish....
    }
  }
}

Print | posted on Thursday, April 05, 2007 9:29 AM |


Feedback

# Link Listing - April 6, 2007

Update Firebug to 1.0.3 [Via: Dion Almaer ] Bob Fox is on a tear with some great MOSS screencasts [Via:... 4/7/2007 12:53 AM | Christopher Steen

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

it displays an error message "The name 'ScriptManager1' does not exist in the current context" 4/17/2007 1:56 AM | pubs

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

It is a requirement to have ScriptManager on the same page to make the UpdatePanel work....please add a ScriptManager on the page. If you have scriptmanager in your Masterpage you need a ScriptManagerProxy on the content page. 4/18/2007 8:50 PM | Shahed Khan

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

Why not just use ScriptManager.RegisterAsyncPostBackControl(button)? 4/24/2007 10:26 AM | JEberlin

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

Thanks for posting this. I tried using the code but it won't work for me. I am dynamically creating imagebuttons inside an update panel. I am also using a masterpage. When I access the Request[ScriptManager1.ID] inside the CreateChildControls method, the value is null. Could this have something to do with me using masterpages? Does anyone know how to get the controlID of the dynamic control makign the asyncpost (when using masterpages)? 7/16/2007 1:39 AM | albdamned

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

hi shahed bhai,
I was just googling for a way to detect which one of the dynamically loaded controls have fired an event and i came across your page. Its quite awesome..like seriously. And i tried to implement this method in my code,but it didnt quite work since i am using dynamically loaded buttons in the headercontent of accordion pane(the buttons and accordion panes are both created dynamically during runtime and added to an accordion). And I need to figure out which one of the buttons(they all have same id)/panes fired this event.

I have emailed you the code and the full message.If you have any suggestion, can you hit me back?
best regards,
Deema


8/2/2007 4:56 PM | deema

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

Hi shahed


i am creating dynamic controls for textbox and fileupload when i click button1.
after that when i click the button2. i am not getting the those values on button2 clicked.
let me know is there any solution please email us..there is no problem either AJax also.we have integrate Ajax in our application.


thanks
rambhopal Reddy 1/20/2008 11:12 PM | Ram bhopal Reddy

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

Thanks for tip!
I will try it for sure
How does it differ from method when we check Request["__EVENTTARGET"] ? (What are advantages/disadvantages of using this) 2/11/2008 5:59 PM | Kirill

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

Nice tip, just slightly off the mark.

I think you will find that you need the UniqueID and not the ID of the script manager (ID may work if the ID and the UniqueID are the same).

I have my ScriptManager in my master page. I have a wrapper property to allow me to access it from my child pages. When access the request I use the following method.

Request[Master.MasterScriptManager.UniqueID];

The output of the unique id of my script manager is: ctl00$ScriptManager1

The value if: ctl00$ScriptManager1|ctl00$cplContent$Wizard1$btnMoreAuthors

Good Luck all... 2/29/2008 3:19 PM | Quinten Miller

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

Partial Class _Default
Inherits System.Web.UI.Page

Shared myCount As Integer = 0
Private dynamicTextBoxes() As TextBox
Private dynamicLabels() As Label

Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Dim myControl As Control = GetPostBackControl(Me.Page)
If (myControl IsNot Nothing) Then
If (myControl.ClientID.ToString() = "btnAddTask") Then
myCount = myCount + 1
ElseIf (myControl.ClientID.ToString() = "btnRemoveTask") Then
myCount = myCount - 1
End If
End If
End Sub

Protected Overrides Sub OnInit(ByVal e As EventArgs)
MyBase.OnInit(e)
dynamicTextBoxes = New TextBox(myCount - 1) {}
dynamicLabels = New Label(myCount - 1) {}
Dim i As Integer
For i = 0 To myCount - 1 Step i + 1
Dim literalBreak As LiteralControl = New LiteralControl("<br /><br />")
myPlaceHolder.Controls.Add(literalBreak)

Dim textBox As TextBox = New TextBox()
textBox.ID = "myTextBox" + i.ToString()
myPlaceHolder.Controls.Add(textBox)
dynamicTextBoxes(i) = textBox


myPlaceHolder.Controls.Add(literalBreak)
myPlaceHolder.Controls.Add(literalBreak)

Dim lblRubric As Label = New Label()
lblRubric.ID = "myLabel" + i.ToString()
lblRubric.Text = "Rubric for Task No : " + i.ToString()
myPlaceHolder.Controls.Add(lblRubric)
dynamicLabels(i) = lblRubric

myPlaceHolder.Controls.Add(literalBreak)
Next
End Sub

Protected Sub btnAddTask_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddTask.Click
' Handled in preInit due to event sequencing.
End Sub

Protected Sub btnRemoveTask_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemoveTask.Click
' Handled in preInit due to event sequencing.
End Sub

Protected Sub MyButton_Click(ByVal sender As Object, ByVal e As EventArgs)
MyLabel.Text = ""
Dim tb As TextBox
For Each tb In dynamicTextBoxes
MyLabel.Text += tb.Text + " :: "
Next

'Dim grd As GridView
'For Each grd In dynamicGrid
' MyLabel.Text += +" :: "
'Next
End Sub

Public Shared Function GetPostBackControl(ByVal thePage As Page) As Control
Dim myControl As Control = Nothing
Dim ctrlName As String = thePage.Request.Params.Get("__EVENTTARGET")
If ((ctrlName IsNot Nothing) And (ctrlName <> String.Empty)) Then
myControl = thePage.FindControl(ctrlName)
Else
For Each Item As String In thePage.Request.Form
Dim c As Control = thePage.FindControl(Item)
If (TypeOf (c) Is System.Web.UI.WebControls.Button) Then
myControl = c
End If
Next

End If
Return myControl
End Function

End Class

This code work fine In Page .

But when i used in Child(Content ) Page . It ll be not working.

How can i find Master Page script Manger in Child Page 7/14/2008 11:59 PM | Bhupendra

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

thx, good article 7/29/2008 4:47 AM | Net framework

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

Hi,
thanks for the post.
but this way the control will be vanished on the postback to server.

Can you suggest me a way to make them(dynamically created controls) persisted across postbacks.

8/13/2008 6:13 PM | nagesh

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.

thx, good article! 9/4/2008 1:06 AM | Guf

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 2 and 4 and type the answer here:

Powered by: