I am building a wizard in asp.net. I have an main aspx page which will have NEXT and PREVIOUS button for Navigation. On click of each NEXT or PREVIOUS appropriate user control will be loaded.
In one user control I have to create dynamic checkboxes as shown below:
Public Class ucQuestion
Inherits System.Web.UI.UserControl
#Region "UserControl Events"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not (Page.IsPostBack) Then
AddControls(0)
End If
Catch ex As Exception
Throw ex
End Try
End Sub
#End Region
Protected Friend Sub AddControls(ByVal iListQuestionCount As Integer)
Try
Dim oExam As New BusinessObject.Wizard.ExamVM
If (System.Web.HttpContext.Current.Session(BusinessLayer.Constants.WizardObjectCollection) IsNot Nothing) Then
oExam = DirectCast(System.Web.HttpContext.Current.Session(BusinessLayer.Constants.WizardObjectCollection), BusinessObject.ExamWizard.ExamVM)
End If
'divQuestion.Controls.Clear()
Dim ctrl As New Literal
ctrl.ID = "lit" + iListQuestionCount.ToString()
ctrl.Text = oExam.Wizard.ExamQuestions(iListQuestionCount).Label
divQuestion.Controls.Add(ctrl)
For iLoopChildCount As Integer = 0 To oExam.Wizard.ExamQuestions(iListQuestionCount).Choices.Count - 1
Dim childctrl As New CheckBox
'childctrl.AutoPostBack = True
childctrl.ID = "chk" + (iLoopChildCount + 1).ToString()
childctrl.Text = oExam.Wizard.ExamQuestions(iListQuestionCount).Choices(iLoopChildCount).Label
childctrl.Checked = oExam.Wizard.ExamQuestions(iListQuestionCount).Choices(iLoopChildCount).IsSelected
'AddHandler childctrl.CheckedChanged, AddressOf OnCheckedClick
divQuestion.Controls.Add(childctrl)
Next
Catch ex As Exception
Throw ex
End Try
End Sub
NoW the problem is in my Main.aspx page if user has selected any checkbox in usercontrol I want to save the value in session on NEXT button Navigation click event.
I tried following code in NEXT Button Click but it was unsucessfull.
For iLoopChildCount As Integer = 0 To oExamQuestions(ListIndex).Choices.Count - 1
Dim ctrl As Control
If (ucQuestion1.FindControl("chk" + (iLoopChildCount + 1).ToString()) IsNot Nothing) Then
ctrl = DirectCast(ucQuestion1.FindControl("chk" + (iLoopChildCount + 1).ToString()), CheckBox)
If (DirectCast(ctrl, CheckBox).Checked) Then
oBallotQuestions(ListIndex).Choices(iLoopChildCount).IsSelected = True
End If
End If
Next
That's the hard way.
Here is the easy way.
Define an interface and implement it in the User Control that represents this action. This might be GetNamesOfSelectedValues or whatever is appropriate. (Technically an interface isn't required, but I find it good practice and it makes for "more well defined contracts" in many cases.)
Use the interface defined on said Child in the Parent page code. Use this only after the OnLoad of the Child Control (which happens after the page load event) or the controls will not be restored yet.
That is, the parent should not know about any controls in the custom User Control.
This approach works well.
Related
I have a 4 tier architecture using asp.net 4.0
1- Web application
2- Business object
3- Business Logic
4- Data Logic
i have used factory method to create dynamic forms. on a radio button list selected index changed event , i want to hide/show a table row which is also created dynamically. table row is available in session. i am using the following code
Private Sub parameter_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim rdbtn As RadioButtonList = DirectCast(sender, RadioButtonList)
Dim selectedText As String = rdbtn.SelectedItem.Text
Dim worksRequiredRowId = SessionManager.getWorksRequiredRowId()
Dim worksRequiredRow As TableRow = CType(sender.FindControl(worksRequiredRowId), TableRow)
If selectedText.ToUpper <> ApplicationConstants.conditionSatisfactory.ToUpper Then
worksRequiredRow.Style.Add("display", "table-row")
Else
worksRequiredRow.Style.Add("display", "none")
End If
Catch ex As Exception
End Try
End Sub
And i get the following error.
Unable to cast object of type
'System.Web.UI.WebControls.RadioButtonList' to type
'System.Web.UI.WebControls.TableRow'.
Please help me to find out the solution.
Best ragards.
You can actually hide that particular item from radio button list instead of converting it into table row. Something like this.
If rdbtn.SelectedItem.Text <> selectedText.ToUpper <> ApplicationConstants.conditionSatisfactory.ToUpper Then
rdbtn.Items(itemIndex).Attributes.CssStyle.Add("display", "none")
End If
I hope this helps.
I think your mistake is confusing the generated HTML markup with the raw ASP.NET markup. RadioButtonList does create an HTML for each item, but you can't access that rows at the server-side (to make them visible or hidden).
You should either use the server-side method mentioned in Bridewin D.P.'s answer or transfer the code to client-side and use Javascript to manipulate the rows.
Server-side would look something like this:
Private Sub parameter_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim rdbtn As RadioButtonList = DirectCast(sender, RadioButtonList)
Dim selectedText As String = rdbtn.SelectedItem.Text
Dim worksRequiredRowId = SessionManager.getWorksRequiredRowId()
Dim style as String
If selectedText.ToUpper <> ApplicationConstants.conditionSatisfactory.ToUpper Then
style= "table-row"
Else
style= "none"
End If
rdbtn.Items(worksRequiredRowId).Attributes.CssStyle.Add("display", style)
Catch ex As Exception
End Try
End Sub
I have a relatively simple ASP.NET problem (I should think) that regrettably I am unable to solve by myself. What I am trying to do is the following:
On a page I load a number of controls (Text Boxes) programmatically;
following this load the user should be able to select a value to load into the Textbox from a panel control that is added to the page following the click of a button
Once the panel is closed, the selected text from the panel should be loaded into the textbox
However, in the vb.net statements below when run the "test" string never makes it to the textbox - any help with resolving this would be greatly appreciated.
Public Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Controls_Load()
End Sub
Public Sub Controls_Load()
Dim ttf_tb As New TextBox With {.ID = "ttf_tb"}
Master_Panel.Controls.Add(ttf_tb)
Dim ttf_button As New Button
Master_Panel.Controls.Add(ttf_button)
AddHandler ttf_button.Click, AddressOf TTF_BUTTON_CLICK
End Sub
Public Sub TTF_BUTTON_CLICK(sender As Object, e As EventArgs)
Dim str As String = sender.id
Dim panel As New Panel
panel.ID = "TTF_Panel"
panel.Width = 300
panel.Height = 300
Master_Panel.Controls.Add(panel)
panel.BackColor = Drawing.Color.Black
panel.Style.Add(HtmlTextWriterStyle.Position, "absolute")
panel.Style.Add(HtmlTextWriterStyle.Left, "200px")
panel.Style.Add(HtmlTextWriterStyle.Top, "100px")
panel.Style.Add(HtmlTextWriterStyle.ZIndex, "100")
Dim CL_Button As New Button
CL_Button.ID = "TTF_Close_" & Replace(str, "TTF_Button_", "")
panel.Controls.Add(CL_Button)
AddHandler CL_Button.Click, AddressOf TTF_Close_Button_Click
End Sub
Public Sub TTF_Close_Button_Click(sender As Object, e As EventArgs)
Dim ttf_tb As TextBox = Master_Panel.FindControl("ttf_tb")
ttf_tb.Text = "Test"
Dim panel As Panel = FindControl("TTF_Panel")
Master_Panel.Controls.Remove(panel)
End Sub
End Class
I think you need to re-create your controls in the Page_Init method. It's been a while since I've done web forms but I think it's something like:
When a user clicks the button a post back is fired. This re-creates a new instance of your class, creates the controls on the page, assigns any form values then calls your Page_Load event.
The problem is you are creating your controls too late, so the forms values are never assigned correctly.
You should create / recreate your dynamic controls in the Init event:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Controls_Load()
End Sub
This should allow you to maintain their state across PostBacks.
For more information about this topic, see the MSDN article on the ASP.NET Page Life Cycle.
I have some code that handles a timer method, that just updates a label and changes it to a last updated at this time.
Protected Sub specialNotesTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles specialNotesTimer.Tick
Label1.Text = "Panel refreshed at: " + DateTime.Now.ToLongTimeString()
End Sub
When it ticks however, any other control on the page cannot be found via a button press. Image buttons or my other dynamically created controls, w.e the case, are missing.
I have a function that finds the fired control on the page, then returns the control so I can determine what to do
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
This works before the timer.tick, but not after. The control won't be listed as an Item in thePage.Request.Form, and it'll throw a null exception, when I know the control is there.
I have a series of controls (3 labels, 3 text boxes, and 2 buttons) that are created when the user clicks a button on my page. The page does its postback with the commands that will generate these controls. However, when I fill in my textboxes and click one of the newly generated buttons (btnCreate), nothing happens, and the page just reloads once again.
What I want to happen is that when the user clicks btnCreate, it fires its function, and puts the TextBox.Text into a database. But again, when btnCreate is clicked, nothing happens.
Here is the code for the generated buttons (It's the same function that generates the text boxes, which I've excluded here):
Protected Sub createSpecialNotes()
Dim btnCreate As Button = New Button
Dim btnClear As Button = New Button
'Place properties
lblSubject.Text = "subject"
lblSubject.ID = "lblSubject"
lblSubject.Width = 700
lblAgenda.Text = "Agenda Note"
lblAgenda.ID = "lblAgenda"
lblAgenda.Width = 700
lblMinutes.Text = "Minutes Note"
lblMinutes.ID = "lblMinutes"
lblMinutes.Width = 700
btnCreate.Text = "Create"
btnCreate.ID = "btnCreate"
btnClear.Text = "Clear"
btnClear.ID = "btnClear"
'Add handlers for buttons
AddHandler btnCreate.Click, AddressOf btnCreate_Click
AddHandler btnClear.Click, AddressOf btnClear_Click
plhCreateSpecialNotes.Controls.Add(btnCreate)
plhCreateSpecialNotes.Controls.Add(btnClear)
End Sub
And for the sake of simplicity, let's just say btnCreate needs only to display the textboxes' contents.
Edit1: The call for create special notes is on page_preInit. It's call consists of the following
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
'Find the control that was fired
Dim controlFired As Control = GetPostBackControl(Me.Page)
If (controlFired IsNot Nothing) Then
If (controlFired.ClientID.ToString() = "btnCreateSpecial") Then
Call createSpecialNotes()
End If
If (controlFired.ClientID.ToString() = "btnCreate") Then
'i've tried putting things here to no avail.
End If
End If
End Sub
The function getpostbackcontrol looks like this
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
I hope this helps to clear things up as to why I'm having trouble.
What would be really useful here is to know when you're calling createSpecialNotes(). But most probably what you are missing is the life-cycle of the page.
Make sure createSpecialNotes() is called OnInit of your page. Anything after that is too late and your event handler won't be fired.
If OnLoad of your page is reached and you haven't yet bound the handler to your control, then it won't be fired.
I recommend that you read this article carefully. http://msdn.microsoft.com/en-us/library/ms178472.aspx
The problem im having is a little complicated to explain, so please bear with me. I have 2 button controls. In the page load, I wanted to know what button created a postback on the page load. Through research I have found this snippet below and it works as expected. So here is my scenario of events that occur when click on the button.
1. Click the button does a postback
2. Runs the function below and tell me the id of the button
3. Runs the clicked event handlers for that button
Protected Sub btnCalc_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCalc.Click
' Do this
End Sub
The problem comes in when I click the second button, it does steps 1 and 2 but NEVER DOES 3. Through testing, I have that it only does 1, 2, and 3 on the first button clicked. I have no clue why this is happening?
Function GetPostBackControlName() As String
Dim control As Control = Nothing
Dim ctrlname As String = Page.Request.Params("__EVENTTARGET")
If ctrlname <> Nothing AndAlso ctrlname <> [String].Empty Then
control = Page.FindControl(ctrlname)
Else
Dim ctrlStr As String = [String].Empty
Dim c As Control = Nothing
For Each ctl As String In Page.Request.Form
c = Page.FindControl(ctl)
If TypeOf c Is System.Web.UI.WebControls.Button Then
control = c
Exit For
End If
Next
End If
Try
Return control.ID.ToString
Catch
Return ""
End Try
End Function
You really should look into just assigning Click event handlers to your buttons. Asp.net was designed purposely so that you wouldn't have to parse through the request object like you are doing above.