Monday, March 26, 2012

Passing variable into ASCX in vb.net

I have an ASCX which I have as the header for all my pages in my site.

In this ASCX page I determine which banner to show. It's been working great so far except now I have to add the capabilities of "zones" for my pages. This means I need to pass a variable to it.

Does anyone have an example of this ? I can't seem to find anything. I'm assuming this can be done.

Thanks alot
mike123Create a public field in the user control. Then on the page that you are including the usercontrol, add the property and the value to the HTML declaration to pass in the value to the usercontrol.

So if you create a public field like so in your usercontrol:

VB:
Public myProperty As String

C#:
public string myProperty;

Then in the HTML portion of the page that has the usercontrol on it, you would have:

<[TagPrefix]:[TagName] ID="myUserControl1" myProperty="This is what I am passing." runat="server" /
Now when the control is rendered, the public field myProperty that was defined in the UserControl has the value of 'This is what I am passing.', without the single quotes.

The TagPrefix and the TagName is defined in the Register tag at the top of the page. If you are using Visual Studio, it will automatically handle that for you when you drag the user control onto the page. All you need to to is put in the myProperty portion in the appropriate tag.
You may add a property in your usercontrol class.
Hi Jimmy,

Thanks for the response. Would you happen to have an example of how this is done? I haven't attempted this before and am unsure how to go about doing that

thanks again
In your ascx class, add this code before page_load event:
Assume your usercontrol called "usercontrol1"
In usercontrol1.ascx.vb


Dim strTest As String = ""
Public Property Test() As String
Get
Return strTest
End Get

Set(ByVal Value As String)
strTest = Value
End Set

In aspx.vb


Protected WithEvents propertyTest As usercontrol1

Private Shadows Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
usercontrol1.Test = "Test"
End Sub

0 comments:

Post a Comment