I am trying to use a property from the code-behind to populate a textbox instead of using in the code-behind textbox.text=. I am using vb.net. Here is the code for the aspx page:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:TextBox runat="server" ID="roleTextBox" Text='<%# CurrentRole.Name%>'></asp:TextBox>
</asp:Content>
Here is the code behind code:
Imports Compass.UI.components
Imports Compass.Core.Domain
Imports Compass.Core.Domain.Model
Namespace app.administration.Roles
Partial Public Class edit
Inherits ClaimUnlockPage
Private _roleRepository As IRoleRepository
Private _roleId As Integer
Private _role As Role
Public Property CurrentRole() As Role
Get
Return _role
End Get
Set(ByVal value As Role)
_role = value
End Set
End Property
Public Property RoleRepository() As IRoleRepository
Get
Return _roleRepository
End Get
Set(ByVal value As IRoleRepository)
_roleRepository = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LoadRole()
End Sub
Private Sub LoadRole()
_roleId = Config.RequestVal("id", Request)
_role = _roleRepository.GetById(_roleId)
End Sub
End Class
End Namespace
When I run the page the text box is empty.
I didn't see roleTextBox.text=value in your code! in LoadRole or anywhere.
And if you try to bind it, you need a static class for Role.
Just for testing try to add the following line in LoadRole
Private Sub LoadRole()
_roleId = Config.RequestVal("id", Request)
_role = _roleRepository.GetById(_roleId)
roleTextBox.text =CrrentRole.Name;
End Sub
if the roleTextBox is still empty then the CurrentRole.Name is empty.
As far as I know you can't bind a property of a control like this (I wish you could but I've never been able to figure out or find an example how to). The way I've always done it is create a protected function to return e.g.
Protected Function GetCurrentRoleName() As String
Return CurrentRole.Name
End Function
And in your markup bind like so
Text='<%# GetCurrentRoleName() %>'
You have to DataBind the container-control which contains your Textbox(f.e. a GridView,UserControl,etc.). So at least your aspx-page must be databound.
"When called on a server control, this method resolves all data-binding expressions in the server control and in any of its child controls."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.CurrentRole = New Role("Administrator")
Me.DataBind() '!!!!!!!
End Sub
Private _currentRole As Role
Protected Property CurrentRole() As Role
Get
Return _currentRole
End Get
Set(ByVal value As Role)
_currentRole = value
End Set
End Property
Public Class Role
Public Sub New(ByVal name As String)
Me.Name = name
End Sub
Public Name As String
End Class
Then you can use your aspx-code to set the TextBox'-text property.
Related
The ASPX that I have is a partial that has a a master page on it and I would like to replace a textbox with new text.
I have a listbox that is created from the data base in the ASCX. I have a text box in the default.aspx page which I would like to change the test if the selected index has changed. I keep getting the error to delcare class, the class definiton for the defualt.aspx.vb is got a definition is below.
Partial Class _Default
Inherits System.Web.UI.Page
Code that sits on default.aspx.vb
Public Sub test(ByVal val As String)
lbl1LoginPage.Text = val
End Sub
VB ascx code to get the value of the selected index
Protected Sub ListBox3_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ListBox3.SelectedIndexChanged
Dim test As String = ListBox3.Text
Dim page As _Default = DirectCast(page, _Default)
page.test(test)
End Sub
You can create a Property in aspx page exposing the text box control say "TextBoxControl" then you can access it in you dropdownlist handler as shown below :
Protected Sub ListBox3_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ListBox3.SelectedIndexChanged
Dim test As String = ListBox3.Text
Dim page As _Default = DirectCast(Me.Page, _Default)
page.TextBoxControl.Text = "Some Text"
End Sub
(I am not well versed with vb.net so syntax may be wrong at some places)
My suggestion is to use a bubble event:
Protected Sub ListBox3_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ListBox3.SelectedIndexChanged
Dim test As String = ListBox3.Text
// this line is in C#. I don't know how it is in VB
RaiseBubbleEvent( this, new CommandEventArgs( "ListBoxText", test ) );
End Sub
this is all in C#!! here is your method in your aspx-page:
protected override bool OnBubbleEvent( object source, EventArgs args )
{
// you can check in addition whether the source is of type of your user control
if ( args is CommandEventArgs )
{
lbl1LoginPage.Text = ((CommandEventArgs)args ).CommandArgument.ToString();
return true;
}
return base.OnBubbleEvent( source, args );
}
UserControl should not call Parent page. It is not a good design.
Instead, you want to bubble up the event from UserControl to the Parent page.
Here is the example -
Child
<asp:ListBox runat="server" ID="ListBox3"
OnSelectedIndexChanged="ListBox3_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
</asp:ListBox>
Public Partial Class Child
Inherits System.Web.UI.UserControl
Public Event ListBox3SelectedIndexChanged As EventHandler
Protected Sub ListBox3_SelectedIndexChanged(sender As Object, e As EventArgs)
RaiseEvent ListBox3SelectedIndexChanged(sender, e)
End Sub
End Class
Parent
<%# Register Src="~/Child.ascx" TagName="Child" TagPrefix="uc1" %>
...
<uc1:Child ID="Child1" runat="server"
OnListBox3SelectedIndexChanged="Child1_ListBox3SelectedIndexChanged" />
Protected Sub Child1_ListBox3SelectedIndexChanged(sender As Object,
e As EventArgs)
Dim listBox3 = TryCast(sender, ListBox)
If listBox3 IsNot Nothing Then
Dim selectedText As String = listBox3.SelectedItem.Text
End If
End Sub
I have the following class:
Public Class HtmlGenericSelfClosingTag
Inherits HtmlGenericControl
Public Sub New()
MyBase.New()
End Sub
Public Sub New(tag As String)
MyBase.New(tag)
End Sub
Public Shadows Property TagName As String
Get
Return MyBase.TagName
End Get
Set(value As String)
MyBase.TagName = value
End Set
End Property
Public Overrides ReadOnly Property Controls As ControlCollection
Get
Throw New Exception("HtmlGenericSelfClosingTag cannot have child controls.")
End Get
End Property
Public Overrides Property InnerHtml As String
Get
Return String.Empty
End Get
Set(value As String)
Throw New Exception("InnerHtml cannot be set on an HtmlGenericSelfClosingTag")
End Set
End Property
Public Overrides Property InnerText As String
Get
Return String.Empty
End Get
Set(value As String)
Throw New Exception("InnerText cannot be set on an HtmlGenericSelfClosingTag")
End Set
End Property
Public Overrides Sub RenderControl(writer As HtmlTextWriter)
MyBase.Render(writer)
writer.Write(HtmlTextWriter.TagLeftChar & Me.TagName)
Attributes.Render(writer)
writer.Write(HtmlTextWriter.SelfClosingTagEnd)
End Sub
End Class
I have declared the control as:
Protected WithEvents MyElement As HtmlGenericSelfClosingTag
I have the html tag defined as:
<HtmlGenericSelfClosingTag ID="MyElement" runat="server" />
I am getting the following error during page render:
The base class includes the field 'MyElement', but its type (MyClass.HtmlGenericSelfClosingTag) is not compatible with the type of control (System.Web.UI.HtmlControls.HtmlGenericControl).
I have searched DuckDuckGo (and, by extension, Google, etc) to find out what else I need to override to make my class compatible with the HtmlGenericControl class, but no dice. I have also checked the MSDN docs but no mention of override requirements. Any ideas?
I was able to resolve the issue by removing the <HtmlGenericSelfClosingTag ID="MyElement" runat="server" /> tag from the aspx file, and simply adding the control directly in code, as in:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.head.Controls.AddAt(0, BaseElement)
End Sub
And to avoid rendering the control twice, I modified the Render code:
Public Overrides Sub RenderControl(writer As HtmlTextWriter)
writer.Write(HtmlTextWriter.TagLeftChar & Me.TagName)
Attributes.Render(writer)
writer.Write(HtmlTextWriter.SelfClosingTagEnd)
End Sub
I'm trying to find a way in which I can create a collection of various webControl's and then add a "onClick" event handler to these various controls, i've tried creating a reimplementation of "webControl" with a registered "onClick" event but I get a typecast error. Could anyone suggest how I could achieve this.
exception:
Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.RadioButtonList' to type 'Club.WebControlButton'.
new webControl class:
<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> Public Class WebControlButton
Inherits WebControl
Implements IPostBackEventHandler
' Define the Click event.
Public Event Click As EventHandler
' Invoke delegates registered with the Click event.
Protected Overridable Sub OnClick(ByVal e As EventArgs)
RaiseEvent Click(Me, e)
End Sub
' Define the method of IPostBackEventHandler that raises change events.
Public Sub RaisePostBackEvent(ByVal eventArgument As String) _
Implements IPostBackEventHandler.RaisePostBackEvent
OnClick(New EventArgs())
End Sub
End Class
Private Sub AddOnClickStringsToElements()
Dim divider As Integer = If(onClickElements.Count > 0, onClickElements.Count, 1)
Dim percentIntervals As Integer = 100 / divider
For Each element As Tuple(Of String, WebControl, Integer) In onClickElements
If element.Item3 < 1 Then
element.Item2.Attributes("onClick") = GetAnimateJavascript(percentIntervals)
Else
element.Item2.Attributes("onClick") = GetAnimateJavascript(element.Item3)
End If
//throws typecast exception here
AddHandler CType(element.Item2, WebControlButton).Click, AddressOf UpdatePercent_OnClick
Next
End Sub
It looks like the onClickElements collection contains an actual RadioButtonList control, not a control which derives from your WebControlButton class.
Any control which you are putting into the onClickElements collection must derive from WebControlButton for that casting operation to work e.g.
Public Class MyRadioButtonList
Inherits WebControlButton
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
' Create your radio button list here..
End Sub
End Class
An easier way would be to make an interface, such as IClickable...something a bit like this..sorry I didn't type it in VS so not sure if I got the syntax exact.
Public Interface IClickable
Public Event OnClick()
End Interface
Public Class MyRadioButtonList
Inherits RadioButtonList
Implements IClickable
Public Event OnClick Implements IClickable.OnClick
Private Sub RaiseOnClickEvent Handles Me.OnSelectedIndexChanged
RaiseEvent OnClick()
End Sub
End Class
And then..
For Each element As Tuple(Of String, WebControl, Integer) In onClickElements
If TypeOf(element.item2) Is IClickable Then
AddHandler CType(element.Item2, IClickable).OnClick, AddressOf UpdatePercent_OnClick
Else
Throw New Exception("A control of type IClickable was expected")
End If
Next
How would you concatenate a string from a resource assembly to an asterisk(*) in the Text property in an asp:Label control?
For example:
<asp:Label ID="someLabel" ...
Text="<%$ ExternalAssembly|FileName, resourceName %>*" runat="server".../>
End result is to display 'Name*'
Thanks
Reference a server-side function to return the desired string.
I apolgize, but this will be in vb.net. However, it is minimal code so I don't think it will be too hard to translate into C# if that's what you need.
Steps
Create the ASP.NET tag for the label control.
Inside the text attribute, insert a data-binding expression for the function getAssembly() . Example: Text='<%# getAssembly("Fullname")%>' We will build this function in a moment. Also note that it accepts a parameter to identify what piece of information you need regarding the assembly. Another common mistake is not using single quotes for the inline expression (because double quotes will conflict with the string parameter).
Import the necessary namespaces System and System.Reflection into the code-behind.
Create the function getAssembly(ByVal InfoItem as String) in the code-behind (details for this function are below).
Add a line in the Sub Page_Load() to bind data to the assemblyLabel control when the page is loaded.
Here is the necessary code in detail for each step:
ASP.NET Tag
<asp:Label ID="assemblyLabel" runat="server" Text='<%# getAssembly("Fullname")%>'></asp:Label>
Function in the Code-Behind
Public Function getAssembly(ByVal InfoItem As String) As String
Dim a As AssemblyName = Assembly.GetExecutingAssembly.GetName()
Select Case InfoItem
Case "Name"
Return a.Name
Case "Fullname"
Return a.FullName
Case "Version"
Return a.Version.ToString
Case Else
Return ""
End Select
End Function
Necessary imports:
Imports System
Imports System.Reflection
Bind the data in Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
assemblyLabel.DataBind()
End Sub
The entire code-behind...
Imports System
Imports System.Reflection
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
assemblyLabel.DataBind()
End Sub
Public Function getAssembly(ByVal InfoItem As String) As String
Dim a As AssemblyName = Assembly.GetExecutingAssembly.GetName()
Select Case InfoItem
Case "Name"
Return a.Name
Case "Fullname"
Return a.FullName
Case "Version"
Return a.Version.ToString
Case Else
Return ""
End Select
End Function
End Class
i have ASP.NET page, its code-behind, and a Class file:
Folder1/page.aspx (asp.net page), it contains a label:
<asp:Label runat="server" ID="Label1" Visible="false"></asp:Label>
Folder1/page.aspx.vb (code-behind), it calls connection.vb like this:
Dim x As New Connection
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
x.checkusernameExists(TextBoxUsername.Text)
' I try to access `Boolean variable` Flag from Class file but I can't.
End Sub
App_Code/connection.vb (a class file that i created):
Public Class Connection
Public Sub checkusernameExists(ByVal username1 As String)
Dim flag as Boolean
' I try to access here `Label1.text` & `Label1.visible` to work on it but I can't.
End Sub
End Class
My Questions
1 - How can I access the Label1 from the ASP.NET page in Connection.vb?
2 - How can I access the Boolean variable from Connection.vb in page.aspx.vb (code behind)?
I am really stuck in this.
Thank you.
Use (public) properties or method parameters.
You have to ask yourself following: why should a class that is responsible for a connection(i assume to database) have access to your GUI at all? Don't hardlink different layers with each other, otherwise you won't be able to use them alone.
I would suggest to let the connection class do it's work and that is not to modify your frontend. Instead the controller (the aspx page) should manage it's GUI and call the connection class, using the return value to determine what to do next with the Label.
So return a Boolean to indicate if the user is valid:
Public Class Connection
Public Shared Function checkusernameExists(ByVal username1 As String)As Boolean
Dim userExists As Boolean
' acces db to check if the username exists '
Return userExists
End Sub
End Class
in your page:
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
Dim userExists As Boolean = Connection.checkusernameExists(TextBoxUsername.Text)
Label1.Visible = userExists
If Label1.Visible Then Label1.Text = "Hello again " & TextBoxUsername.Text
End Sub
make flag as property and set this property in checkusernameExists function
Public Class Connection
Public Property Flag as Boolean
Public Sub checkusernameExists(ByVal username1 As String)
// set flag here
Flag = True // or whateever value returned from the database
' I try to access here `Label1.text` & `Label1.visible` to work on it but I can't.
End Sub
End Class
and access this instance level property in page.aspx.vb file
Dim x As New Connection
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
x.checkusernameExists(TextBoxUsername.Text)
Label1.Visible= x.Flag;
' I try to access `Boolean variable` Flag from Class file but I can't.
End Sub
You can use Function to return value and pass label as parameter.
Public Function SaveChanges(ByRef Label1 As Label, ByVal username1 As String) As Boolean
{
Return True
}
It would be better if you pass the label properties to function instead of passing the object of label as it couple up two classes.