Problem while Creating Dynamic ModalPopup - asp.net

i want to create a modalpopup dynamically but i come across a problem.I pasted my sub here and i dont know what to do for that problem.When i want to show modalpopup,it says
"Control 'mdldelete2' of type 'ModalPopupExtender' must be placed inside a form tag with runat=server." How can i solve this?
Public Sub Raise_Alarm(ByRef p_Page As Page,
ByRef p_AssignedButton As System.Web.UI.WebControls.Button,
ByVal p_Message As String)
Dim mdldelete2 As Global.AjaxControlToolkit.ModalPopupExtender =
p_Page.Page.FindControl("mdldelete2")
If mdldelete2 Is Nothing Then
mdldelete2 = New Global.AjaxControlToolkit.ModalPopupExtender
End If
With mdldelete2
.TargetControlID = p_AssignedButton.ID
.PopupControlID = "pnlDelete"
.ID = "mdldelete2"
.BackgroundCssClass = "modalBackground"
.OkControlID = "btnDeleteOk"
.CancelControlID = "btnDeleteCancel"
End With
p_Page.Controls.Add(mdldelete2)
Dim mylabel As Label
mylabel = p_Page.FindControl("lblStatus")
mylabel.Text = p_Message
mdldelete2.Show()
End Sub

Really, you should be adding the mdldelete2 control to the Controls collection of the Form control, rather than the Page directly - that might help.
I often find it's easier to add a PlaceHolder control to the page for this sort of thing - it doesn't add anything directly to the page, but gives you a named container to find and add controls to.
Also, just a point - if you did find an instance of the control with the Page.FindControl method, then you don't need to add it to a form collection again, as it's already in there.

Looks like you need to add a ScriptManager control to the aspx
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

Related

how to refer to a user control's "strong" type

I have code like this which loads a control from an .ascx file, calls some methods of the control, then renders it:
Option Explicit Off
Sub renderMyControl(p As Page)
Dim ctrl as Object = p.LoadControl("path/to/myControl.ascx")
' ... do stuff with ctrl ...
ctrl.DoThing1()
' ...
ctrl.RenderControl(New HtmlTextWriter(p.Response.Out))
End Sub
This code only works because Explicit is off. I would like to use CType to convert the control to its "strong type" (and get rid of Option Explicit Off) but I don't know how to add a reference to the type. How can I do this?
VB.NET or C#? I think you got your samples mixed up a bit. :)
This will work - in VB.NET:
Sub renderMyControl(ByVal p As Page)
Dim ctrl = CType(p.LoadControl("myControl.ascx"), myControl)
ctrl.DoThing1()
ctrl.RenderControl(New HtmlTextWriter(p.Response.Output))
End Sub

dynamically set control ID

i have few texboxt and dropdownlist, which their id would be something like "txtName1, txtName2, txtName3..." and "ddlAction1, ddlAction2, ddlAction3...."! I would to to dynamically set the textboxt and dropdownlist id into something like this:
for i as integer = 0 to 6
a = txtName+i.text
b = ddlAction+i.SelectedValue
next i
Need help from you guys to do this! thanks....
The key is FindControl, which looks up a control by its expected ID:
For i As Integer = 0 To 5
Dim txt As TextBox = TryCast(Me.Page.FindControl("txtName" & i.ToString()), TextBox)
Dim ddl As DropDownList = TryCast(Me.Page.FindControl("ddlAction" & i.ToString()), DropDownList)
If txt IsNot Nothing AndAlso ddl IsNot Nothing Then
Dim a As String = txt.Text
Dim b As String = ddl.SelectedValue
End If
Next
It will return null/nothing if a control with that ID isn't found.
Note that FindControl will only search the given control's (or Page's) immediate children, not the entire control tree. To search recursively, you need to use your own FindControl method.
Private Function FindControlRecursive(ByVal control As Control, ByVal id As String) As Control
Dim returnControl As Control = control.FindControl(id)
If returnControl Is Nothing Then
For Each child As Control In control.Controls
returnControl = child.FindControlRecursive(id)
If returnControl IsNot Nothing AndAlso returnControl.ID = id Then
Return returnControl
End If
Next
End If
Return returnControl
End Function
.Net requires you to resolve your variable names at compile time, rather than runtime like your code is trying to do. This is a good thing, as it prevents you from making certain kinds of errors. But it does mean you'll need to look at an alternative approach for this particular problem.
One option is a FindControl -based method. But odds are the controls you care about are grouped together on the page. If they aren't already, put them in a common container control, like a panel. Then you can do something like this (requires System.Linq):
For Each t As TextBox In MyContainer.Controls.OfType(Of TextBox)()
a = t.Text
Next t
For Each d As DropDownList In MyContainer.Controls.OfType(Of DropDownList)()
b = d.SelectedValue
Next d
Also, I hope you're really doing something other than assignment inside your loop. Otherwise, most of the work is for nothing as you will exit the loop having simply assigned the value from the last iteration to your variable.
Finally, it seems like these controls might work in pairs. To me, that's a situation that calls out for you to implement a user control.
I'm not a webforms expert, but I believe the page stores a reference to each control present in the page.
You can think of webforms like an n-ary tree... each control has a parent and can have 0 to many children. So, if these are static controls you should just be able to grab a reference to their parent and iterate over that... with no need for the children's ids.
Also, you can query for children based on their id... something like myControl["myID1"] so you can concat the number with the string and get the control that way.
Lastly, if these are purely dynamic controls, i.e. you don't know how many there are, just store references to them in an ordered collection and iterate over them that way.
EDIT:
Here we go:
WebControl myControl;
myControl.Controls.Add(someControlReference);
Then, to grab a control by ID:
WebControl someControl = myControl.FindControl("someControlID1");
From there you can do like:
string a = someControl.Text

ASP.NET Dynamic User Controls

I'm sure this question has been asked a million times, however I haven't been able to find an answer that solves my problem.
I am programmatically adding some custom user controls to a PlaceHolder which I have on a simple aspx page. All of the user controls Postback's work correctly except for one which has a Gridview on it.
For some reason any postback that gets fired from within this control, does not call the specified event on the first click, however all future clicks it will work fine. I have no idea why this is the case, but many solutions I have found, suggest adding an ID to the ascx User Control, however this doesn't work in my case.
I've taken a look at the source file for the page that gets generated before and after the first click, javascript used for calling the postback changes, i.e
Before first click: onclick="javascript:__doPostBack('tmpControlID$sgvPrimaryEmploymentHistory','Select$0')"
After first click: onclick="javascript:__doPostBack('OFFHome1$tmpControlID$sgvPrimaryEmploymentHistory','Select$0')"
OFFHome1 is the parent user control which exists on the aspx page. All other controls are added to a placeholder in this control, i.e.
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="OFFHome.ascx.vb" Inherits="UmbracoUserControls.OFFHome" %>
<asp:PlaceHolder ID="phOFFSection" runat="server"></asp:PlaceHolder>
Nothing to complicated. Then in the code behind the controls are loaded into the placeholder using the following:
Private Sub LoadNextOFFStep()
Dim ControlName As String = "TestControl.ascx"
phOFFSection.Controls.Clear()
If ControlName IsNot Nothing AndAlso ControlName <> String.Empty Then
Dim NewControl As Object = LoadControl(ControlName)
With NewControl
.ID = USERCONTROLNAME
Dim StepCompleted As Boolean = .FillControl()
If StepCompleted Then
Exit Sub
End If
Dim AllowSkip As Boolean = .AllowSkip()
btnSkip.Visible = AllowSkip
End With
phOFFSection.Controls.Add(NewControl)
End If
End Sub
Again, nothing overly complicated. The USERCONTROLNAME is just a const with the value "tmpControlID" in it.
The control that is giving me trouble is a little complicated, I was originally using a custom GridView control that we have created, but have removed it and replaced it with the standard asp one to see if the problem still occurs, and it does.
Any button, on control which fires off a postback will fail the first time, and all future click will work correctly. On the first click the Page_Load event will get called, but that is it.
What am I doing wrong??
After far too much time spent on this, I have finally worked it out.
It was to do with the order of events, however just not where I had thought. The FillControl function was getting called before User Control had been added to the PlaceHolder. I changed this so that it gets called after the User Control was added to the PlaceHolder and now it works first time.
Basically the code looks like this now:
Private Sub LoadNextOFFStep()
Dim ControlName As String = "TestControl.ascx"
phOFFSection.Controls.Clear()
If ControlName IsNot Nothing AndAlso ControlName <> String.Empty Then
Dim NewControl As Object = LoadControl(ControlName)
With NewControl
.ID = USERCONTROLNAME
Dim AllowSkip As Boolean = .AllowSkip()
btnSkip.Visible = AllowSkip
End With
phOFFSection.Controls.Add(NewControl)
Dim StepCompleted As Boolean = CType(phOFFSection.Controls(0), Object).FillControl()
If StepCompleted Then
LoadNextOFFStep()
Exit Sub
End If
End If
End Sub
Thanks for everyone's help.
Well... the answer to the first question is simple: It fails the first time because the ID of the control (or rather, in the postback script) is different on subsequent page loads. It works on subsequent clicks because the control ID stays the same.
Now as to WHY that is... much tougher! But probably something to do with the order of operations here.
Try explicitly setting the NamingContainer value for NewControl:
With NewControl
.NamingContainer = OffHomeOne; // whatever
.ID = USERCONTROLNAME

How to enable/disable web elements of a parent aspx page from the child ascx page?

I have an aspx page with three web controls: one to control the List Users page, one to control the Edit Users page, and one to control the Add User page. I have discovered a method for accessing these elements, but it seems to be limited. Here is what I have done:
Protected Sub editUser(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
'set selected user from gridview.
Dim index As Integer = e.NewEditIndex
Dim userId As Integer = gvListUsers.DataKeys(index).Value
Session.Item("SelectedUserId") = userId
'show edit page, hide list and add page.
With Page.Form.Controls(1)
.Controls(getControlId("loadAddUser")).Visible = False
.Controls(getControlId("loadEditUser")).Visible = True
.Controls(getControlId("loadListUser")).Visible = False
End With
End Sub
The getControlId function looks like this:
Public Function getControlId(ByVal control As String) As Integer
Dim enumer As System.Collections.IEnumerator = Page.Form.Controls.Item(1).Controls.GetEnumerator
Dim i As Integer
For i = 0 To (Page.Form.Controls.Item(1).Controls.Count - 1)
If Page.Form.Controls(1).Controls.Item(i).ID = control Then
Return i
End If
Next
Return Nothing
End Function
This works in most cases. However, I am unable to access the "enabled" attribute of these web controls. Why is this, and how might I access that attribute?
Thanks :)
You could raise events from your UserControls which you subscribe to in the parent ASPX page. In the parent page event action you could enable/disable your controls,
Here's an example of events in UserControls: http://codebetter.com/blogs/brendan.tompkins/archive/2004/10/06/Easily-Raise-Events-From-ASP.NET-ASCX-User-Controls.aspx
Something else to think about: are you getting any benefit from moving this code into usercontrols? Would any of the individual controls be re-usable on their own? Creating tightly coupled controls that rely on each other being present doesn't give you much re-usability of the individual controls.
Visible is a property provided by the System.Web.UI.Control class, which is why you can access it directly. Enabled is not a property on this class, so you need to map the control object to a variable of the type of your custom control class if you want to access the Enabled property.
Dim myControl As TheAddUserControl
With Page.Form.Controls(1)
myControl = .Controls(getControlId("loadAddUser"))
myControl.Enabled = False
.Controls(getControlId("loadEditUser")).Visible = True
.Controls(getControlId("loadListUser")).Visible = False
End With
To expose an Enabled property in you user control:
Public Property Enabled As Boolean
Get
Return (Child1.Enabled And Child2.Enabled And Child3.Enabled)
End Get
Set(ByVal value As Boolean)
Child1.Enabled = value
Child2.Enabled = value
Child3.Enabled = value
End Set
End Poperty

previouspage.findcontrol getting variable from previous page

i am trying to retain the value of a variable from a previous page. i believe this is the C# way to do this, but i would like the vb.net way can someone please help:
TextBox myTxt = (TextBox)Page.PreviousPage.FindControl("previousPageTextBox");
currentPageTextBox.text = myTxt.Text;
i would like to know how to code this in vb.net
i tried this:
Dim myTxt As TextBox = CType(Page.PreviousPage.FindControl("Textbox1"), TextBox)
TextBox1.Text = myTxt.Text
but i got this error msg:
use the new keyword to create an object instance
This should do it, also make sure you are using Server.Transfer to go between pages.. but I am sure you already know this:
Dim myTxt as TextBox = CType(Page.PreviousPage.FindControl("previousPageTextBox"), TextBox)
currentPageTextBox.text = myTxt.Text
dim txt as TextBox =CType( Page.PreviousPage.FindControl("previousPageTextBox"),
TextBox)
currentPageTextBox.Text = txt.Text
PS:- You need to set the previous page in the page where you want to find the control.
<%# PreviousPageType VirtualPath="~/Test.aspx" %>
Also better way will be to create an function on previous page which returns the text in textbox.
internal function TextBoxText() as string
return myTextPage.Text
end function
and use this on next page like this:
currentPageTextbox.Text = Page.PrevousPage.TextBoxText
let me know if this works because I've not used vb for long long time.
PPS:- It is only available if you user Server.Transfer or go to currentPage using some asp.net contorl like LinkButton from simple href links PreviousPage is null

Resources