Is there any way to directly access a field of class in the aspx page?
I have tried this:
In the aspx page I have added:
<form id="LoginForm" runat="server">
<asp:Label Text='<%# Eval("Test") %>' runat="server" ID="jym" />
</form>
and in the backend class of this page I have declared a property as:
private string test;
public string Test {
get {
return test;
}
set {
test = value;
}
}
This property is initialized in Page_Load() as: Test = "JYM";
But the problem is I am unable to see this value in the browser. The tag is rendered into <span/> but without any content.
What I am doing wrong?
Are you calling Page.DataBind() in Page_Load()?
You are using the # data binding operator in your embedded code block. The values that you bind to the control will only show after you have called DataBind() from either the control or the page (which will in turn call it for each control on the page).
If you only want to bind a value to that single label control you could just call jym.DataBind().
I would however suggest using a more descriptive name (id) for the Label control so it is clearer in the code about what is being databound.
See this page for more details.
UPDATE (extra info requested by OP in comment)
So you have 3 options:
1.
Call DataBind() as suggested above.
2.
Don't use a server side control for the label. Just use plain HTML and then you can use the following syntax:
<p><%= Test %></p>
3.
Set the value of the label in the code behind. For example in your page load you might have the following:
protected void Page_Load(object sender, EventArgs e)
{
jym.Text = Test;
}
You may want to use <%= this.Test%>. You can also do this.jym.Text=Test; in the Page Load evt.
Related
I have an HTML table code (starts with <table> and ends with </table>), how can I make my asp web page to add this table programmatically?
If you have purely HTML code generated in server side, then you can add that HTML code having <Table> into your asp page like this.
Add a placeholder to aspx page like this.
<asp:PlaceHolder ID="plc" runat="server" />
In page_load event write this.
String str = "<table><tr><td>TD VALUE</td></tr></table>";
plc.Controls.Add(new LiteralControl(str));
This will emit html code , and place them to placeholder.
ASSUMPTION This is just a readonly html code , that you wan to show in page, you are not intended to get those value in server side code on post back. Nor there is any editable field inside the generated table.
if you want to access this table programatically then use
<table runat="server" id="YOUR_ID"></TABLE>
it will then let you access this control through asp.net
Either redo it in asp:table as you already mentioned or add runat="server" to your existing table and you will be able to alter it in codebehind.
After runat = server you can do things like
protected void Page_Load(object sender, EventArgs e)
{
var str= tbl1.Rows[0].Cells[2].InnerHtml;
}
But I would probably redo it in <asp:table> if you are using webforms. See full example here
Add rows to a table dynamically
I have Page1.aspx containing
Name: <asp:TextBox ID="txt1" runat="server" />
Page2.aspx tries to access its contents by
TextBox txt2 = (TextBox)PreviousPage.FindControl("txt1");
However I end up getting an Object reference not set to instance of an object exception
I've used PreviousPage before and have had success with this snippet of code I found elsewhere online (Can't remember where I found it!)
So..
Option 1:
On your first page you have your button that takes you to the second page, you need to set the PostBackUrl property to the new page url:
<asp:Button ID="button1" Runat="server" Text="submit" PostBackUrl="~/Page2.aspx" />
(This is presuming that your 1st page is a form that redirects to your Page2.aspx)
Then in the new page's code behind you need to write something along the lines of this:
public void page_load()
{
if(!IsPostBack)
{
TextBox tb = (TextBox)PreviousPage.FindControl("txt2");
Response.Write(tb.Text);}
}
You will need to transfer the value of the previous page's txt2.Text to a textbox or label on the new page if you are wanting to do any more postbacks on the second page, otherwise you will lose that value.
Option 2:
You could also use a Session variable surely to store your data?!
Session["text"] = txt2.Text;
Once your'e in the new page, the last page is probably gone, I'd suggest transferring your data over the session.
I have a some pages that are slightly different, but all have the same "action buttons" that do the same tasks for each page. Instead of duplicating the code, I made a user control that includes buttons that perform actions - but there's one action I can't seem to do.
Each page has a textbox (that's not inside the user control, as it's in a different location of the page). When I click the "Save comment" button (that is within the User Control), I can't seem to access the text in the Textbox.
I have tried using something like this:
TextBox txtComments = (TextBox)this.Parent.FindControl("txtComments");
SaveChanges(txtComments.Text);
...but txtComments comes back as null.
So, I'm wondering if this is possible, or perhaps if there's a better way to do what I'm trying to do?
Edit: The Textbox is in a Placeholder on the original page...
Edit 2: Posting minified solution - still can't figure this one out.
Edit 3: Removed solution to conserve space - resolved the issue.
My solution ended up being surprisingly simple....
TextBox txt = this.Parent.Parent.FindControl("ContentPlaceHolder2").FindControl("TextBox1") as TextBox;
if (txt != null) Label1.Text = txt.Text;
Where I was going wrong before was that I was using the wrong ContentPlaceHolder ID. I was using the ID of the placeholder in the page, rather than the ID from the Master Page.
Use the Page property exposed by WebControl, the common base of server-side controls.
You could even then cast the instance to the specific page type and access the control directly (if scope allows), instead of using FindControl.
To recap the situation - you need to do a FindControl of a control on a page from a child control, however -
Your project has a MasterPage, in which case this.Page seems to not work, and we use this.Parent instead
Your "target" control is inside a PlaceHolder, which itself is inside a ContentPlaceHolder, so it's not as simple as just this.Parent.FindControl()
Your child ASCX control that is trying to find the "target" control, in this case a textbox, is actually in ANOTHER ContentPlaceHolder, so again, this.Parent.Parent or whatever will not work.
Since you mentioned after my initial this.Parent answer about the controls being in a different ContentPlaceHolder from each other, and in another child control, it complicates your query a bit.
Based on these criteria, and the fact that you at least know the contentPlaceHolder control which contains (somewhere inside of it) your target TextBox, here's some code I wrote that works for me in a new ASP.net Web Forms application:
It recursively checks controls collection of the ContentPlaceHolder you pass to it, and finds your control.
Just pass the ControlID and ContentPlaceHolderID, and it will recursively find it.
This code is a replacement for my original one below with the same project, located inside of ChildControl.ascx.cs file:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;
using System.Collections.Generic;
namespace FindControlTest
{
public partial class ChildControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
var textBoxTest = FindControlInContentPlaceHolder("TextBoxTest", "FeaturedContent") as TextBox;
Response.Write(textBoxTest.Text);
Response.End();
}
private Control FindControlInContentPlaceHolder(string controlID, string contentPlaceHolderID)
{
if (null == this.Page ||
null == this.Page.Master)
{
return null;
}
var contentPlaceHolder = this.Page.Master.FindControl(contentPlaceHolderID);
var control = getChildControl(controlID, contentPlaceHolder);
return control;
}
private Control getChildControl(string controlID, Control currentControl)
{
if (currentControl.HasControls())
{
foreach(Control childControl in currentControl.Controls)
{
var foundControl = childControl.FindControl(controlID);
if (null != foundControl)
{
return foundControl;
}
else
{
return getChildControl(controlID, childControl);
}
}
}
return null;
}
}
}
Note:
I tried this in a few events and even on Init() I was able to get the TextBox value
If you are seeing a null it is likely due to an incorrect ID being passed or a situation I didn't encounter yet. If you edit your question with additional info (as there has been a lot of it) and show what variable is null, it can be resolved.
Note that I added some complexity to my MasterPage, such as a PlaceHolder inside a Panel, and then put the ContentPlaceHolder in there, and the code still works. I even compiled for .net 4.5, 4.0, 3.5, and 3.0 thinking maybe FindControl works differently with MasterPages, but still it works every time. You may need to post some additional MarkUp if you still get a null.
The Rest of the Test Project
The Page (based on default MasterPage)
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FindControlTest._Default" %>
<%# Register TagName="ChildControl" TagPrefix="uc1" Src="~/ChildControl.ascx" %>
<asp:Content runat="server" ContentPlaceHolderID="FeaturedContent">
<asp:PlaceHolder ID="PlaceHolderTest" runat="server">
<asp:TextBox ID="TextBoxTest" Text="Hello!" runat="server"/>
</asp:PlaceHolder>
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<uc1:ChildControl id="ChildControlTest" runat="server" />
</asp:Content>
I added a control called ChildControl.ascx that only has this in it:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ChildControl.ascx.cs" Inherits="FindControlTest.ChildControl" %>
Hello child!
The result is "Hello!" on the page.
If you want to access the textbox property in codebehind as intellisence property, simply make it a string property in the user control.
1. In the user control, create a public string property that returns textbox string value..
public string MyText
{
get
{
return txt1.Text;
}
}
2. Register the user control on the page
<%# Register TagPrefix="uc" TagName="MyControl" Src="~/mycontrol.ascx" />
and declare it..
<uc:MyControl ID="control1" runat="server" />
3. From the codebehind now you can read the property..
Response.Write(control1.MyText);
Hope it helps
Thanks...
I'm using ajaxFileUpload as described here: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx
It is working fine except when I have multiple file upload controls on the same page. Specifically, I am trying to upload different files for different questions. When I upload the first on the page, it works fine, but the one lower down on the page will only upload it's file into the answer for the first question.
I'm not sure that makes sense... so it may help you to know that my page is populated with questions dynamically using ascx files. The document ascx file looks like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Document.ascx.cs" Inherits="ScholarshipApplication.controls.questions.Document" %>
<ajaxToolkit:AjaxFileUpload OnUploadComplete="UploadComplete" ID="FileUploadControl" MaximumNumberOfFiles="1" runat="server" AllowedFileTypes="png,jpg,jpeg,pdf,tiff,tif,gif" />
<asp:LinkButton ID="downloadButton" runat="server" CausesValidation="false" OnClick="downloadButton_Click" />
And the code behind:
public void UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
entry.data = e.FileName;
entry.setDocumentData(e.GetContents());
this.downloadButton.Text = e.FileName;
}
My initial thoughts are that somehow I need to help the control's generated javascript to know which question it should be triggering when.
I believe this is a bug in control or this was implemented by some non-obvious reason. Actually, this control doesn't support multiple instances on a page. Consider to use AsyncFileUpload control instead or customize a bit sources of the AjaxFileUpload control. If you prefer second option then you need to download sources from here: http://ajaxcontroltoolkit.codeplex.com/SourceControl/BrowseLatest and change AjaxFileUpload.cs file (here is a path: /Server/AjaxControlToolkit/AjaxFileUpload/AjaxFileUpload.cs). What you need to do is to change ContextKey constant to property for combining context key guid with unique id of control:
public class AjaxFileUpload : ScriptControlBase
{
private const string ContextKeySuffix = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}";
private string ContextKey
{
get { return this.UniqueID + "_" + ContextKeySuffix; }
}
Actually, if you'll look on PreRender method of AjaxFileUpload class you'll easy realize reson for such behavior of this control (the first control handle uploads from all sibling controls on a page).
as per my understanding You need a hidden field variable to identify your question id IN UserControl:
<input type="hidden" id="hdnQuestionId" runat="server"/>
while populating/generating question you need to set this variable , and when you upload the doc , fetch this hidden value and use it.
I created a data attribute named "data-upload-type" on ALL AjaxFileUpload controls and set it to the name of the type. Then I set up the client call to grab that value and set a cookie with the same value. The cookie IS received on the server side functions and I branch based on the value I receive.
Here is an example:
function StartUpload(sender, args) {
var t = $(sender._element).attr('data-upload-type');
document.cookie = 'upload-type=' + $(sender._element).attr('data-upload-type') + ';';
}
<asp:AjaxFileUpload ID="afuUploader1" runat="server" OnClientUploadStart="StartUpload" OnUploadComplete="UploadComplete" OnClientUploadComplete="UploadComplete" data-upload-type="UploadType2"></asp:AjaxFileUpload>
Then in your server side upload call simply check Response.Cookies("upload-type").
Works like a charm!
In code behind page I create a variable like this (it belongs to one of the class)
string login_status = "you are not logged in";
I want to show this variable value in my Default.aspx page. What do I do?
You can create a variable of type string with protected access modifier and call it on your web page using:
<%= login_status %>
Drop a label onto your aspx page:
<asp:Label ID="Label1" runat="server"></asp:Label>
then in the codebehind, say:
Label1.Text = login_status;
Add a label control onto the default.aspx page. It will automatically be named Label1.
From your code behind you can place your string into the label.
Label1.Text = login_status
http://haacked.com/archive/2007/02/15/asp.net_tip_-_use_the_label_control_correctly.aspx
you can use asp.Literal control instead of Label.
You should add a control to the page (label, literal) that will display this nicely and set it's value in the code behind.
You can also user runat="server" on any html tag to set it's inner html (etc) in the code behind.
Finally if you want to do it the 'quick' way you can put <%=login_status%> in the markup.
There are multiple ways you can do
First Variables you trying to access should be protected or public
Then you can access these variables like
<% Response.Write(login_status); %>
or
<%= login_status%>
or you can use control like asp control like labels and change its Text property on code behind