posts - 234, comments - 480, trackbacks - 56

My Links

News




I am born in Bangladesh and currently live in Melbourne, Australia. I am a co-founder and core developer of Pageflakes www.pageflakes.com and CEO at Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh.

I also created SmartCodeGenerator

Some of 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

Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

# 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
Gravatar

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

Hi,

I m doing as per suggest.

But when I click button (I just display one label in other update panel) then after all the buttons are invisible.

Can u solve my problem

Thanks
Ketan
9/26/2008 1:51 AM | Ketan
Gravatar

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

please see my code below :

Public Sub AddItem()
Dim iditem As Integer = 0
enSubItem._ID_PRODUK = ddl_id_produk_custom.SelectedValue
rows = conPesan.GetRows(enSubItem)

For index As Integer = 0 To rows - 1

Dim div As HtmlGenericControl = New HtmlGenericControl("div")
Dim label_item As Label = New Label
Dim ddl As DropDownList = New DropDownList


iditem = 10001 + index
enSubItem._ID_ITEM = String.Concat("IT", iditem.ToString())

NamaItem = conPesan.GetNamaItem(enSubItem)
div.Attributes.Add("class", "CustomProduk")

ddl.DataSource = SqlDataSource_warna
ddl.DataSourceID = String.Empty
ddl.DataTextField = "WARNA"
ddl.DataValueField = "ID_WARNA"
ddl.DataBind()

label_item.Text = NamaItem + ":"
ddl.ID = "ddl_warna_" + index.ToString()
label_item.ID = "lbl_item_" + index.ToString()
div.Controls.Add(label_item)
div.Controls.Add(ddl)

ln_ddl.Add("ddl_warna_" + index.ToString())
ln_lbl.Add("lbl_item_" + index.ToString())

PH_CustomProduk.Controls.Add(div)
Next
End Sub

this is my code, i want put control to page each control is binding from database (label n dropdownlist)..the problem is how to post the input back to the database when user press the button, how to retrieve value from each control...cant u help me

please reply me at angela.mellysa@yahoo.com

regards

angela
11/6/2008 7:51 PM | angela
Gravatar

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

Thanks Shahed and Quinten Miller.

I've used this code to access the dynamically created LinkButtons through the MasterPage's ScriptManager and it works great!

Here is the code:




This is in a foreach loop:

LinkButton deleteLinkButton = new LinkButton();
deleteLinkButton.ID = "deleteReminder_" + reminder.Id.ToString();
deleteLinkButton.CommandName = "DeleteReminder";
deleteLinkButton.CommandArgument = reminder.Id.ToString();
deleteLinkButton.Text = "[ X ]";
deleteLinkButton.Command += deleteReminderButton_OnClick;



protected override void CreateChildControls()
{
base.CreateChildControls();

ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);

if (scriptManager.IsInAsyncPostBack)
{
string fromWhere = Request[scriptManager.UniqueID];
}
}



Cheers,
Mike

11/7/2008 7:08 PM | Mike Gurevich
Gravatar

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

Thankx good help
2/14/2009 10:26 PM | Bony
Gravatar

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

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.
3/15/2009 1:46 AM | dll
Gravatar

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

hi... i want to display "FileUpload" control dynamically which is present in "ToolBox" when i press the "LinkButton" control to "Attach more Files" as the option is provided in "YAHOO".
can some one help me...


Cheers,
AMOGH
4/8/2009 11:13 PM | AMOGH
Gravatar

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

Thanks admin nice ost
9/3/2009 9:51 AM | sesli sohbet
Gravatar

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

hi... i want to display "FileUpload" control dynamically which is present in "ToolBox" when i press the "LinkButton" control to "Attach more Files" as the option is provided in "YAHOO".
can some one help me...
Thanks admin
tatil
tekne
9/3/2009 9:52 AM | manken
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: