Transfer between Page and Web control? - asp.net

There are test.aspx page and test.ascx web user control.
I have a button in test.aspx = btn_test and above code in my button is :
Dim ct As Control = Page.LoadControl("test.ascx")
Panel1.Controls.Add(ct)
There is a dropdownlist with value 1 to 10 in test.aspx and there is label_test in test.ascx
I need some code when test.ascx loading, get dropdownlist.selectedvalue and show it in label_test.
Please help me !

There are a number of ways to implement this. One you could try would be to cast the test.ascx web control being loaded like so (replace TestControl with the class name for the control):
Dim ct As TestControl = CType(Page.LoadControl("test.ascx"), TestControl)
And then create a public property in the control which you would use to set the value from the DropDownList.
Dim ct As TestControl = CType(Page.LoadControl("test.ascx"), TestControl)
ct.DropDownListValue = DropDownList.SelectedItem.Value
Panel1.Controls.Add(ct)
This property would then be used to set the labels value (either directly using the set accessor or via a method within the test.ascx control).

Related

How can I pass a textbox value from one aspx page to another aspx page in VB.net?

I am trying to pass a textbox value from one aspx page to another aspx page. I have tried - Previous page property and Application variable. I do not want to use cookies for this textbox. I have tried the below code in page 2 and it throws me "Object reference not set to an instance of an object." error.
Any help would be appreciated.
If Not IsNothing(Request.Cookies("IMF")("UserID")) Then
lblUserID.Text = (Request.Cookies("IMF")("UserID").ToString())
Dim txt As TextBox
txt = CType(Page.PreviousPage.FindControl("txtUsername"), TextBox)
If Not IsNothing(txt) Then
lblUserName.Text = Server.HtmlEncode(txt.Text)
Else
lblUserName.Text = "[Name Not available]"
End If
End If

Grabbing a property from an aspx page to an ascx toolbar in VB

I have a web page (aspx)- Purchasing page, with a ascx toolbar - Export Toolbar, that is used to export the data (either .xls or .csv).
I need to grab the Name of the Supplier from the Purchasing page and insert that value into the name of the export file on the ascx toolbar.
On the Purchasing page there is a ddl where the user can select the supplier and a grid that will display all the data. Above the grid there is the tool bar with an export button. I need to be able to grab the text of the dropdown list and utilize that on the ExportToolbar.ascx.vb page so I can take that text and insert it into the name.
I was trying to use a public property get and set method but it was not working. How would I go about grabbing that selected text from the Supplier ddl?
Conventional thinking goes like this: an ascx can be hosted on any aspx page. So usually it is bad form for an ascx to access properties of its host page. It is much more proper for the ascx to have a public property and the aspx will push the value into the ascx (as needed).
However, if you really want to go this route, the .Page property (of the ascx) referrs to the host page. If you cast it to the (stronger) type(name) of the host, you can get to the hosts properties. Like this:
'if your host page is called HostPage (and the class name is the same)
Dim host as HostPage = CType(me.Page, HostPage)
'now refer to the controls on the host (aspx) page
dim example as string
example = host.txtExample.Text
Keep in mind, this will cause errors if your ascx is hosted on several pages.
You can use an event form this purpose. Define the event on the UserControl like this:
Public BeforeExportEventArgs
Inherits EventArgs
Public Property FileName As String
End Class
Public Class ToolbarControl
Inherits UserControl
Public Event BeforeExport As EventHandler(Of BeforeExportEventArgs)
Public Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
' Retrieve File Name
Dim beforeExpEventArgs As New BeforeExportEventArgs()
RaiseEvent BeforeExport(Me, beforeExpEventArgs)
' Set default filename if not provided by an event handler
If String.IsNullOrEmpty(beforeExpEventArgs.FileName) Then
beforeExpEventArgs.FileName = "DefaultFileName.csv"
End If
' Export data
End Class
Add an event handler to the form that hosts the UserControl:
Public Class WebForm1
Inherits Page
' ...
Public Sub expToolbar_BeforeExport(sender As Object, e As BeforeExportEventArgs) Handles expToolbar.BeforeExport
e.FileName = ddlSupplier.Text + ".csv"
End Sub
' ...
End Class
This way, you avoid tight coupling between the UserControl and the Page. The pages that host the UserControl can set a specific filename, but don't have to.
What I ended up doing was this-
On the ascx page I created a public property-
Public Property SupplierSelection As String
Get
Return Convert.ToString(ViewState.Item("SupplierSelection"))
End Get
Set(ByVal value As String)
ViewState.Add("SupplierSelection", value)
End Set
End Property
And then on the aspx page I added this on the load grid event-
SupergridToolbar1.SupplierSelection = ddlStrategy.SelectedItem.Text.ToString()
I was then able to use the Supplier Selection on the ascx page. Thanks for the help!

Unit testing custom user controls - Why is the control not initialized?

With a custom control (lets call it TwoLists) that contains two asp:DropDownList (defined in .ascx), I create an instance of TwoLists in my unit test, to find its child lists are nothing.
Public Sub test_TwoLists()
Dim instance As TwoLists = New TwoLists()
Dim list1 As DropDownList = instance.FindControl("list1")
Dim list2 As DropDownList = instance.FindControl("list2")
Assert.IsNotNull(list1)
Assert.IsNotNull(list2)
End Sub
Why is the control not initialized with it's child controls?
Note: This control is created/intialised and works fine when being used in an .aspx and I navigate to the page.

Need to reference controls/properties in an ascx control (asp.net, written in vb)

I have a user control that I'm adding to a webpage dynamically. The ascx has a couple of controls that I want to have access to at runtime. I can access the ascx itself, but none of the controls on the ascx are available. I have tried adding a simple public variable and also tried adding a public property to the ascx, but I am unable to get access to either of them at design time (compile errors). I would appreciate any ideas - I'm stuck... :-)
I added the following to the code-behind of the ascx control:
Public Property areaCode() As String
Get
Return iebEmpPhoneAreacode.Text
End Get
Set(ByVal value As String)
iebEmpPhoneAreacode.Text = value
End Set
End Property
Public AreaCodeStr As String = ""
and am trying to use variations of the following to access the property/ascx controls:
For Each ctrl As Control In pnlPhones.Controls
If ((TypeOf ctrl Is ctrlPhone) And (ctrl.ID = vbNullString)) Then
(DirectCast(ctrl, ctrlPhone)).AreaCodeStr = "test"
'or try this
ctrl.areaCode = "test"
End If
Next
The hosting page should have an #Reference Directive pointing to the loaded ascx so it will be compiled with the page.
Something like:
<%# Reference VirutalPath="YourReferenceControl.ascx" %>
This should go in the directives area somewhere below the #Page directive.
http://msdn.microsoft.com/en-us/library/w70c655a.aspx

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

Resources