Geeks With Blogs

News Awarded Microsoft MVP C#.NET - 2007, 2008 and 2009


I am born in Bangladesh and currently live in Melbourne, Australia. I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net)and born in Bangladesh.
I am founder and Chief Executive Officer of
Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Co-founder and core developer of Pageflakes www.pageflakes.com.
Simplexhub, is on its mission to build a smart virtual community in Bangladesh and recently launched beta realestatebazaar.com.bd an ASP.NET MVC application written in C#.NET.


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

Shahed Khan blog

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....
    }
  }
}

Posted on Thursday, April 5, 2007 9:29 AM | Back to top


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

# Link Listing - April 6, 2007
Requesting Gravatar...
Update Firebug to 1.0.3 [Via: Dion Almaer ] Bob Fox is on a tear with some great MOSS screencasts [Via:...
Left by Christopher Steen on Apr 07, 2007 12:53 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
it displays an error message "The name 'ScriptManager1' does not exist in the current context"
Left by pubs on Apr 17, 2007 1:56 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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.
Left by Shahed Khan on Apr 18, 2007 8:50 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
Why not just use ScriptManager.RegisterAsyncPostBackControl(button)?
Left by JEberlin on Apr 24, 2007 10:26 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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)?
Left by albdamned on Jul 16, 2007 1:39 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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


Left by deema on Aug 02, 2007 4:56 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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
Left by Ram bhopal Reddy on Jan 20, 2008 11:12 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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)
Left by Kirill on Feb 11, 2008 5:59 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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...
Left by Quinten Miller on Feb 29, 2008 3:19 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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
Left by Bhupendra on Jul 14, 2008 11:59 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
thx, good article
Left by Net framework on Jul 29, 2008 4:47 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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.

Left by nagesh on Aug 13, 2008 6:13 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
thx, good article!
Left by Guf on Sep 04, 2008 1:06 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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
Left by Ketan on Sep 26, 2008 1:51 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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
Left by angela on Nov 06, 2008 7:51 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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

Left by Mike Gurevich on Nov 07, 2008 7:08 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
Thankx good help
Left by Bony on Feb 14, 2009 10:26 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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.
Left by dll on Mar 15, 2009 1:46 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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
Left by AMOGH on Apr 08, 2009 11:13 PM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
Thanks admin nice ost
Left by sesli sohbet on Sep 03, 2009 9:51 AM

# re: Ajax.Asp.Net Tips and Tricks: Adding Dynamic Controls to UpdatePanel and Identifying what control has triggered the event.
Requesting Gravatar...
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
Left by manken on Sep 03, 2009 9:52 AM

Your comment:
 (will show your gravatar)


Copyright © Shahed Khan | Powered by: GeeksWithBlogs.net | Join free