Solved

Dynamically Build a Server Side Button Object

Posted on 2009-05-12
14
373 Views
Last Modified: 2013-12-26
I've built an application that gets information from a database and dynamically displays controls
in asp.net pages.  The application is used to build surveys.  The users create their surveys using objects such as textboxes, dropdowns, radio buttons.  I'm using an HTMLGenericControl with a divcontainer to hold the objects.  When the app runs the divcontainer displays the survey.  Everything works so far but I'm having a problem building a server side button object that will work the same way.  The only button object I've been able to create so far has an OnClientClick method but no OnClick method.  Does anyone know how to build a server side button object?
0
Comment
Question by:nmachin
  • 5
  • 5
  • 4
14 Comments
 
LVL 10

Expert Comment

by:MaxOvrdrv2
Comment Utility
you need to assign a handler function to it when you create it... example... hope this helps:


Dim chkage As New CheckBox

chkage.ID = "chkAgeDep" + ControlID.ToString

chkage.AutoPostBack = True

AddHandler chkage.CheckedChanged, AddressOf chkageDep_ButtonHandler
 
 

Public Sub chkageDep_ButtonHandler(ByVal sender As Object, ByVal e As EventArgs)
 

End Sub

Open in new window

0
 

Author Comment

by:nmachin
Comment Utility
I've already successfully created other objects such as checkboxes, radiobuttons, textboxes but I can't seem to create a button object the same way.  Any suggestions for button objects specifically?
0
 
LVL 10

Expert Comment

by:MaxOvrdrv2
Comment Utility
the button should be called the exact same way... example:


Dim btnage As New Button

btnage.ID = "btnAgeDep" + ControlID.ToString

btnage.AutoPostBack = True

AddHandler btnage.Click, AddressOf btnageDep_ButtonHandler

 

 

Public Sub btnageDep_ButtonHandler(ByVal sender As Object, ByVal e As EventArgs)

 

End Sub
 
 

this should work perfectly... i have a version working in front of me right now... 

Open in new window

0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
Comment Utility
As MaxOvrdrv2 mentions you can create button dyanmically but for using the functionality of server-side click event, you have to attach it to a Sub Routine using AddHandler.
Please see the attached code snippet. Hope this helps.

Dim btn As New Button()

btn.ID = "btn_" & SomeRandomNumber.ToString()

AddHandler btn.Click, AddressOf ButtonClickEventHandler
 

Private Sub ButtonClickEventHandler(ByVal sender As Object, ByVal e As System.EventArgs)

'Code here for handling click event of dynamically generated button
 

'use this object for recognizing which button has been pressed using various properties as set in earlier code

Dim btn As Button = CType(sender, Button)
 

End Sub

Open in new window

0
 

Author Comment

by:nmachin
Comment Utility
I'm trying to use your example but intellisense is not giving me "ButtonClickEventHandler" as an option.  Do I need to include something else?
0
 
LVL 10

Expert Comment

by:MaxOvrdrv2
Comment Utility
no no no... use my example since his example is the exact same as mine... and intellisense won't give you anything because "ButtonClickEventHandler" is the NAME OF THE FUNCTION YOU WILL USE TO HANDLE THE CLICK...
0
 

Author Comment

by:nmachin
Comment Utility
I know.  I saw how dumb my question was after I submitted it.  I'm trying out your solutions right now and will give points once I'm done.  Thanks.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 10

Expert Comment

by:MaxOvrdrv2
Comment Utility
no one said dumb... the way he wrote it would've made me think of inherent function too... althought there's little way to call it differently... maybe in -=text=- would've made it clearer... anyway... no problems, take your time.
0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
Comment Utility
I suggested the ButtonClickEventHandler to let you know that you can name anything to this routine and it is not necessarily mandatory to use the style which VS2008 automatically adds for design-time created objects.
0
 

Author Comment

by:nmachin
Comment Utility
Ok, I have my code like MaxOvrdrv2 except it doesn't give me the option of autopostback.  When the button is clicked, it refreshes the page but doesn't hit the event handler.

Dim btnEdit As New Button
btnEdit.ID = "btnEditQ"
btnEdit.Text = "Edit"
AddHandler btnEdit.Click, AddressOf ButtonClickEventHandler

Private Sub ButtonClickEventHandler(ByVal sender As Object, ByVal e As System.EventArgs)
      Response.Redirect("EditQuestion.aspx?surveyid='" & SurveyID.Value & "'&questionid='" & QuestionID.Value & "'")
End Sub
0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
Comment Utility
You must add the code to create dynamic controls in Page_Init event so each time page is initialized the control(s) could be created again so they might get appropriately wired with the events they are being hooked with using AddHandler keyword.
Please use the code provided below.

Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
 

	Dim btnEdit As New Button()

	btnEdit.ID = "btnEditQ"

	btnEdit.Text = "Edit"

	btnEdit.CausesValidation = True
 

	AddHandler btnEdit.Click, AddressOf ButtonClickEventHandler
 

	Form.Controls.Add(btnEdit)
 

End Sub
 

Protected Sub ButtonClickEventHandler(ByVal sender As Object, ByVal e As System.EventArgs)
 

	Response.Write("Dynamic Button Click Event fired. Control's ID = " & CType(sender, Button).ID)
 

End Sub

Open in new window

0
 

Author Comment

by:nmachin
Comment Utility
As I said before I'm building my pages dynamically and can't just add the button to the form.  The placement needs to be specific as in the code below.  If the question is a textbox, this code will run and place the button next to the textbox.  Each case will be different as to where the button will be placed.  I'm a beginner so either I don't understand what you guys are showing me or maybe it works for you but not for what I'm doing.

Case 1
                        
divContainer.Controls.Add(new LiteralControl("<br/>"))
divContainer.Controls.Add(new LiteralControl(strQuestion))
divContainer.Controls.Add(New LiteralControl("<br/>"))
Dim box As New TextBox
divContainer.Controls.Add(box)
divContainer.Controls.Add(btnEdit)
divContainer.Controls.Add(new LiteralControl("<br/>"))
divContainer.Controls.Add(new LiteralControl("<br/>"))                        
0
 
LVL 10

Accepted Solution

by:
MaxOvrdrv2 earned 250 total points
Comment Utility
Yeah... that's the problem with dynamic controls... they're just that, dynamic... so every time there's a postback, you need to re-create the controls in order for them to be valid... in the page_load, you must call a function to create all of your dynamic controls, or else it just won't call the handler... it's pretty stupid like that. They should make a setting when you create controls in the back-end to something like:

dim btn as new button
btn.Persists=true

but unfortunately, we don't have that luxury.

So for your problem here, i would suggest saving the current layout somewhere, and then based on that layout, building the dynamic controls each time the page loads. if you want more info on what i mean by "re-creating" your dynamic controls each time, let me know and i'll explain the reasoning why in more details.
0
 
LVL 11

Assisted Solution

by:Muhammad Ousama Ghazali
Muhammad Ousama Ghazali earned 250 total points
Comment Utility
Adding of the button to the form is provided as an example. You should do a little more at your end to create all your dynamic controls there instead of the button in Page_Init event.
And surely, you can use your own logic of Select Case to load various different dynamic controls but I think you need to use Visible property of these controls if you wish to hide/unhide them on certain postbacks. For example, you must write code to create all dynamic controls for all your Case values. But additionally, set those controls to hide whom you wish to not to appear on first load and unhide them in any event firing on postback caused by a control either placed at design time or dynamically (use the event provided).
Further, for entering dynamic controls at specific locations, you can use an alternative statement: Contros.AddAt() which accepts first parameter value to be index position of the control being added as second parameter.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now