referencing a ASP:TextBox from CodeFile - asp.net

I have 2 ASP controls in a page called Play.aspx:
<asp:TextBox ID="txtGuess" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit Guess" OnClick="PostGuess" />
The code at the top of my page is:
<%# Page Language="VB" AutoEventWireup="false" Debug="false" Inherits="Play" CodeFile="Play.aspx.vb" %>
In the CodeFile (Play.aspx.vb) I have a procedure called PostGuess which tries to reference the TextBox using the code: txtGuess.text
Visual Studio 2008 gives this error: Name 'txtGuess' is not declared.
When I access the page in a browser, I get: 'txtGuess' is not declared. It may be inaccessible due to its protection level.
This is the contents of the Play.aspx.designer.vb:
Option Strict On
Option Explicit On
Partial Public Class Play
Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead
Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm
Protected WithEvents ScriptManager1 As Global.System.Web.UI.ScriptManager
Protected WithEvents LoginView1 As Global.System.Web.UI.WebControls.LoginView
End Class
It might be an easy fix, I am not very good at this, please help!

Declaring
Protected WithEvents txtGuess As Global.System.Web.UI.WebControls.TextBox
in the Play.aspx.vb file should be the ticket.

Related

asp button click event

I am using C#.net for creating an aspx page (Visual Studio 2010).
I have copied most of the template code from online ( HTML ) but when I drop a button of asp and double click it, it doesn't redirect to the code behind page but, instead creates "onclick=btnSubmit_Click" event in the source code.
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Height="30px"
Width="100px" **onclick="btnSubmit_Click"** />
Ideally it should go to the code behind page and allow event handling stuffs, I have no idea why this is happening.
My question is:
1. What do I do in order to get redirected like normal asp pages in Visual Studio
2. If possible, can someone explain what am I doing wrong here?
**I did get a way around it by using javascript
<script type="text/javascript" runat="server">
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
txtName.Text="btn submit clicked"
End Sub
please make sure that your <%Page directive has mentioned CodeBehind file.
i.e
something like this
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/example.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Example.default" %>
this will be on the top of your aspx page
Please try with the below methods.
Method 1:
Based on what I found here: http://forums.asp.net/t/1229894.aspx/1
Right click on your solution explorer.
Add New Item -> Class File.
Name the file as the name of your aspx eg: Default.aspx.cs
When it asks you the file should be in app_code click "no".
In your aspx in page attribute add
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
Similarly in your class file that you just added remove everything. Your class should look like this:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
Method 2: while adding new page please make sure the place code in separate file box is checked

Referencing a ASP:TextBox control - run time error

I have a file called Play.aspx with these controls:
<asp:TextBox ID="txtGuess" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit Guess" OnClick="PostGuess" />
The Sub "PostGuess" is in the CodeFile (Play.aspx.vb) and a line in this Sub references the TextBox using txtGuess.Text
I also have this line in Play.aspx.vb:
Protected WithEvents txtGuess As Global.System.Web.UI.WebControls.TextBox
This is the contents of my Play.aspx.designer.vb file:
Option Strict On
Option Explicit On
Partial Public Class Play
Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead
Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm
Protected WithEvents ScriptManager1 As Global.System.Web.UI.ScriptManager
Protected WithEvents LoginView1 As Global.System.Web.UI.WebControls.LoginView
When I run the web app, I put some text in txtGuess and click Button1 and it gives me this error on the txtGuess.Text:
System.NullReferenceException: Object reference not set to an instance of an object
Any ideas? Cheers.
Issued has been FIXED
The problem was the textbox was inside a ASP:LoginView control

Web Forms error message: "This is not scriptlet. Will be output as plain text"

In my ASP .NET Web Forms I have the following declarative code:
<asp:TextBox runat="server" ID="txtbox" CssClass='<%=TEXTBOX_CSS_CLASS%>' />
The constant TEXTBOX_CSS_CLASS is defined in a base class that the page's code-behind class inherits from:
public class MyPageBase : Page
{
protected internal const string TEXTBOX_CSS_CLASS = "myClass";
}
The edit-time compiler however warns me that "This is not scriptlet [sic]. Will output as plain text".
True to its word, the css class is rendered as literally "<%=TEXTBOX_CSS_CLASS%>".
What does this error message mean and is there a workaround so I can still use a constant in a base class?
You cannot use <%= ... %> to set properties of server-side controls.
Inline expressions <% %> can only be used at
aspx page or user control's top document level, but can not be embeded in
server control's tag attribute (such as <asp:Button... Text =<% %> ..>).
If your TextBox is inside a DataBound controls such as GridView, ListView .. you can use: <%# %> syntax. OR you can call explicitly DataBind() on the control from code-behind or inline server script.
<asp:TextBox runat="server" ID="txtbox" class='<%# TEXTBOX_CSS_CLASS %>' />
// code Behind file
protected void Page_Load(object sender, EventArgs e)
{
txtbox.DataBind();
}
ASP.NET includes few built-in expression builders that allows you to extract custom application settings and connection string information from the web.config file. Example:
Resources
ConnectionStrings
AppSettings
So, if you want to retrieve an application setting named className from the <appSettings> portion of the web.config file, you can use the following expression:
<asp:TextBox runat="server" Text="<%$ AppSettings:className %>" />
However, above snippet isn't a standard for reading classnames from Appsettings.
You can build and use either your own Custom ExpressionBuilders or Use code behind as:
txtbox.CssClass = TEXTBOX_CSS_CLASS;
Check this link on building Custom Expression builders.
Once you build your custom Expression you can display value like:
<asp:TextBox Text="<%$ SetValue:SomeParamName %>"
ID="setting"
runat="server" />
The problem is that you can't mix runat=server controls with <%= .. %>code blocks. The correct way would be to use code behind: txtbox.CssClass = TEXTBOX_CSS_CLASS;.
This will work.
Mark up
<asp:TextBox runat="server" ID="txtbox" class='<%# TEXTBOX_CSS_CLASS %>' />
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtbox.DataBind();
}
}
But its a lot cleaner to access the CssClass property of the asp:TextBox on Page_Load

Using ASPX Web User Control with Visual Studio 2010

I am trying to implement a Web User Control into one of my APSX pages but keep getting the following warning:
Element 'IntFilter' is not a known element. This can occur if there is a compilation error in the Web site, or the web.config file is missing.
The user control is defined in the same web project as the aspx page.
Question:
How do I resolve this warning (I do not want to move the control to a separate project)?
Also, what do I need to do to enable IntelliSense for this control so I can set its FilterTypeSelection property from ASPX?
Code for "~/FilterControls/IntFilter.ascx"
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="IntFilter.ascx.vb" Inherits="StaffSupport.Filters.IntegerFilter" %>
<asp:DropDownList ID="typeFilterDropDownList" runat="server">
<asp:ListItem Selected="True" Text ="Any" Value="-1" />
<asp:ListItem Selected="False" Text ="Equal" Value= "0" />
</asp:DropDownList><br />
<asp:TextBox ID="TextBox1" runat="server" /><asp:CheckBox ID="CheckBox1" runat="server" Text="Inclusive" /><br />
<asp:TextBox ID="TextBox2" runat="server" /><asp:CheckBox ID="CheckBox2" runat="server" Text="Inclusive" /><br />
Code for "~/FilterControls/IntFilter.ascx.vb"
Namespace Filters
Public Class IntegerFilter
Inherits System.Web.UI.UserControl
Public Enum NumberFilterTypes As SByte
Any = -1
Equals = 0
End Enum
Public Property FilterTypeSelection As NumberFilterTypes
Get
Dim value As SByte
If Not Integer.TryParse(typeFilterDropDownList.SelectedValue, value) Then
value = -1
End If
Return CType(value, NumberFilterTypes)
End Get
Set(value As NumberFilterTypes)
typeFilterDropDownList.SelectedValue = CSByte(value)
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
End Namespace
Code for "OpenCases.aspx"
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/StaffSite.Master" CodeBehind="OpenCases.aspx.vb" Inherits="StaffSupport.OpenCases" %>
<%# Register TagPrefix="filters" TagName="IntFilter" src="~/FilterControls/IntFilter.ascx" %>
<asp:Content ID="bodyContent" ContentPlaceHolderID="cphBody" runat="server">
ID<br />
<filters:IntFilter ID="IntFilter1" runat="server" />
</asp:Content>
Code for "OpenCases.aspx.vb"
Public Class OpenCases
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.ViewStateMode = UI.ViewStateMode.Disabled
End Sub
Update 2012/02/21:
Fixed the "filters" vs "filter" miss match.
Also of note, if you drag the control from the Solution Explorer to the page in Design view it will add the references you need (though it was still generating the warning for me). If you drag it to the page in source view it will add an a tag with a href to the element.
Update 2012/02/21 b:
Found the solution, see my answer below.
Apparently you have to reference both the ASCX page and the assembly.
If you drag the ASCX page from the "Solution Explorer" window to the Design view for the page you are editing it will add the reference for the ASCX page, but you will have to add the assembly reference manually.
OpenCases.aspx
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/StaffSite.Master" CodeBehind="OpenCases.aspx.vb" Inherits="StaffSupport.OpenCases" %>
<%# Register Assembly="StaffSupport" Namespace="StaffSupport.Filters" TagPrefix="filters" %><%-- Assembly Reference --%>
<%# Register TagPrefix="filters" TagName="IntFilter" src="~/FilterControls/IntFilter.ascx" %>
<asp:Content ID="bodyContent" ContentPlaceHolderID="cphBody" runat="server">
ID<br />
<filters:IntFilter ID="IntFilter1" runat="server" />
</asp:Content>
Note: beware of object type collisions. For example the following would also work:
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/StaffSite.Master" CodeBehind="OpenCases.aspx.vb" Inherits="StaffSupport.OpenCases" %>
<%# Register Assembly="StaffSupport" Namespace="StaffSupport.Filters" TagPrefix="pre1" %><%-- Assembly Reference --%>
<%# Register TagPrefix="pre2" TagName="IntFilter" src="~/FilterControls/IntFilter.ascx" %>
<asp:Content ID="bodyContent" ContentPlaceHolderID="cphBody" runat="server">
ID<br />
<pre1:IntFilter ID="IntFilter1" runat="server" />
</asp:Content>
This is why it started working for me Friday after I posted this, I had added a custom control which implemented System.Web.UI.WebControls.TextBox so I could drag and drop it from the Toolbox. Since it was in the same namespace the control added the assembly reference when it added the control to the page.
Note: if you are referencing dll files which are contained in your project then you may need to remove the page registrations, build, then add the page registrations back. Otherwise the compiler may complain that the dll files are not in the bin.
Update: 2013/04/18
It appears you only need to add the assembly reference if the UserControl is not defined in the same namespace.
If the parrent is defined in Proj.Presentation and the UserControl is defined in Proj.Presentation then you should not need the assembly reference.
If the parrent is defined in Proj.Page and the UserControl is defined in Proj.Page.UserControl then you should not need the assembly reference.
If the parrent is defined in Proj.Page and the UserControl is defined in Proj.UserControl then you need the assembly reference.
The control is declared as:
<%# Register TagPrefix="filters"
and in the markup
<filter:IntFilter
These must match.
You are registering a different prefix from the one you're attempting to use.
You can either change this:
<filter:IntFilter ID="IntFilter1" runat="server" />
to this:
<filters:IntFilter ID="IntFilter1" runat="server" />
Or change this:
<%# Register TagPrefix="filters" TagName="IntFilter"
to this:
<%# Register TagPrefix="filter" TagName="IntFilter"
Close Visual Studio, delete the schema cache, and re-open Visual Studio. You can find the schemas under something like:
C:\Users\Pavel\AppData\Roaming\Microsoft\VisualStudio\10.0\ReflectedSchemas
It is safe to delete all files in this folder.
Delete the contents of that above folder, and all is well.

Pass Link-Button Click from One User Control to Another

I have two user controls on the same page. One contains a ListView that displays navigation links, the second user control should be updated when user clicks on the buttonlink in the ListView. How can I do this?
UserControl A should handle the button-click and raise a custom event declared in the UserControl
The page handles this event and calls a public method of UserControl B that updates it's content
You could pass necessary informations from UserControl A to page via EventArgs(or pass the UserControl itself as argument and use it's public properties).
The page then passes the arguments to UserControl B via method parameter or by changing it's public properties before calling the Update-Method.
http://msdn.microsoft.com/en-us/library/fb3w5b53.aspx
http://chiragrdarji.blogspot.com/2007/08/raise-event-from-user-control-to-main.html
Here is the sample code you've requested.
Sorry for the meaningless naming but you haven't told what's this all about. You should use readable variables,properties,method and event-names instead.
Reduced UserControl A with a ListView:
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="UsercontrolA.ascx.vb" Inherits="WebApplication1.UserControlA" %>
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1"
CommandName="LinkClick"
CommandArgument='<%#Eval("ID") %>'
runat="server"
Text='<%#Eval("Text") %>'></asp:LinkButton>
</ItemTemplate>
</asp:ListView>
Removed the ListView databinding from codebehind because that doesn't matter. The important part is handling the ListView's ItemCommand and raising the custom event:
Public Event LinkClicked(sender As UserControlA, id As Int32)
Private Sub LV_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListView1.ItemCommand
If e.CommandName = "LinkClick" Then
Dim id = CType(e.CommandArgument, Int32)
' This is the best way for UC's to commmunicate with the page: '
RaiseEvent LinkClicked(Me, id)
End If
End Sub
Simple UserControl B with nothing more than a Label(ascx):
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="UserControlB.ascx.vb" Inherits="WebApplication1.UserControlB" %>
<asp:Label ID="Label1" runat="server"></asp:Label>
With an Update-Method in codebehind:
Public Sub Update(showID As Int32)
Me.Label1.Text = String.Format("Link {0} clicked", showID.ToString)
End Sub
Finally, here is the Page(aspx)
<uc1:UsercontrolA ID="UC_A" runat="server" />
<br />
<uc2:UserControlB ID="UC_B" runat="server" />
It controls both UserControls. It handles the event from UserControl A and calls the Update-Method that UserControl B provides:
Private Sub LinkClicked(sender As UserControlA, id As Integer) Handles UC_A.LinkClicked
Me.UC_B.Update(id)
End Sub
The advantage of this event-approach is that UserControls stay being reusable. You can use UserControl A in other pages as well even when they don't handle this event. It's part of the controller to decide what is needed and what should be done.
UserControls as a rule should not depend on specific controllers, otherwise they are hard-linked and not reusable. That would be also a good source for nasty erros. A UserControl might be a controller for other nested (User-)Controls but not for the page itself.
Communication Summary:
Page -> UserControl -> public properties and methods
UserControl -> Page -> Events
UserControl -> UserControl -> the controller-UserControl adopts the page-role(see above)

Resources