Reading controls from previous page in asp.net - c#

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.

Related

Viewstate issue when dynamically adding controls in ASP.net

Markup looks like this:
<form id="form1" runat="server">
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Do Something" />
</form>
Code behind looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
txt1.Visible = false;
Form.Controls.AddAt(0, new TextBox() { ID = "blah", Text = "blah", EnableViewState = true });
}
The problem is that when I click on the button, txt1 becomes visible again, even though I had set it's visibility to hidden. Viewstate should have retained it's visibility to hidden but for some reason does not.
Important: This only happens when I dynamically add a control using Form.Controls.AddAt. Doing so seems to mess up the viewstate for all controls after the dynamically added control.
Any ideas why? Or how to use AddAt without messing up the viewstate for all subsequent controls on the page?
Like Stilgar said, add the control in Init() instead.
The issue is that ViewState is loaded according to controls' indices between Init() and Load(), and you're messing with the order of the controls after that point. In other words, the ViewState mechanism thinks it needs to set the second TextBox's Visible property to false, but txt1 is the first TextBox at the time it makes that evaluation.
It used to be that ViewState was loaded by a control's ID (which was a FAR superior/more predictable approach), but the ASP.NET team flubbed things up big time in more recent versions of the framework.
See here for more info on page lifecycle and ViewState:
Last event in page that can still affect a page's viewstate

C#/asp.net geting error when sending data from one page to another [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Send data from one page to another in C# ASP.Net
Hi I am trying to send data from one page to another in asp.net I found various methods of doing so and am gona try a few to se how they work but I seem to be getting an error on my first attempt.Here is my code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Go"
PostBackUrl="~/Default2.aspx" />
<br />
I am sending the data from Default.aspx to Default2.aspx.
At the Default2.aspx in the Page_Load method I wrote this to retrieve the data:
if (Page.PreviousPage != null)
{
string txtBox1 = ((TextBox)Page.PreviousPage.FindControl("TextBox1")).Text;
}
From what I read on MSDN this should work but I must be missing something because when I pres the button to send the data and Default2.aspx loads I get an error page that looks like this:
if you use master page for Default.aspx then Page.PreviousPage.FindControl doesn't work. Because when using masterpage, all controls in Default.aspx are placed in ContentPlaceHolder not directy in Form. So you can use below code:
Page.PreviousPage.Form.FindControl("yourContentPlaceHolderID").FindControl("TextBox1");
i assume you use masterpage. Otherwise your first code must work. In addition if you dont use masterpage and textbox is placed in PlaceHolder or Panel, your code won't work as well. FindControl doesnt recursively search in child container controls.
See the link. MSDN
Page.PreviousPage is only available when using Server.Transfer to redirect to a new page. If this is a standard GET or POST, or Response.Redirect then this code will not work.
From your previous page. Use Server.Transfer to be able to access the previous page data.

ASP.NET Expression: Accessing the Property of a Class

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.

Sharepoint Webpart posting data to Application Page via PostBackUrl

I have a Webpart that contains a couple of dropdowns on an update panel. There is a submit button that has the PostBackUrl set to a sharepoint Application Page
<asp:DropDownList ID="ClassSelector" runat="server" Enabled="False"
AutoPostBack="True" onselectedindexchanged="ClassSelector_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-null-">Select Class...</asp:ListItem>
<asp:ListItem Value="1">Class 1</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSubmit" runat="server" Text="Show Page" Enabled="False"
PostBackUrl="~/_layouts/MyWebParts/MyAppPage.aspx" />
This works in redirecting the browser to the Application Page I have created, but I am having trouble accessing the form data.
On the Page_Load function of the Application Page I have the following debugging code.
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
foreach (String s in Page.Request.Form.AllKeys)
{
Label1.Text += s + ": " + Page.Request.Form[s] + "<br />";
}
}
This shows that the data I need has in fact been posted to the page.
ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$SemesterSelector: 28
ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$ClassSelector: 11-0021-A
But when I try to access this as:
Page.Request.Form["ClassSelector"]
Nothing is returned. I know I must be missing something simple here, but I am not sure what.
Any help is greatly appreciated.
Ah, the ASP.NET master page prefix problem! One of my favorites.
The master page for your application page puts a prefix in front of your server-side controls so that they will be unique. If you end up access your control via the Form collection, you have to access it using not only the control ID, but also the ContentPlaceholder prefix. That's why you see such a large ID dumped out of your debugging logic.
If you want to programmatically get to the ID of the control, you can use FindControl, but you'll have to target the apppropriate content placeholder scope for this. Here's a good tutorial/explanation here (which really emphasizes how complex this can get!).
Of course, the other option you can use is just hard-coding the control id based on what you're seeing from your debugging code...but that won't be reliable if you change content placeholders or more your control to a different container.
I guess the answer depends on how static your controls will be.
Hope this helps. Good luck!!
Well to access it that way you would have to use
Page.Request.Form["ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$ClassSelector"]
As you can actually see from your code where you set the label text to s plus Request.Form[s]

IsPostBack always returns false

Every time I test the IsPostBack in PageLoad() false is returned whether or not post data is present. My first reaction was to check to see if the runat="server" tag was missing from the form or submit button. However, they were all added and the WriteEmail.aspx page still always returns false for IsPostBack. I have also tried using IsCrossPagePostBack in place of IsPostBack.
ListInstructors.aspx:
<form runat="server" method="post" action="WriteEmail.aspx">
...
<input type="submit" id="writeEmail" value="Write Email" runat="server" />
</form>
WriteEmail.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Redirect("ListInstructors.aspx");
}
}
Post != Postback. A postback is when you post back to the same page. The action on your form is posting to a new page.
It looks like all you're doing is using the WriteEmail.aspx page to send a message and then going back to where you just were. You're not even displaying a form to collect the text there. It's a very... Classic ASP-ish... way to handle things.
Instead, put the code you use to send a message in class separate class and if needed put the class in the App_Code folder. Also change the submit button to an <asp:button ... /> Then you can just call it the code from the server's Click event for your button and never leave your ListInstructors.aspx page.
In response to your comment: No. From MSDN:
... make a cross-page request by assigning a page URL to the PostBackUrl property of a button control that implements the IButtonControl interface.
The IsPostBack is not true because the form is not being submitted from the WriteEmail.aspx page; submitting a form from the same page is what causes a PostBack. If you submitted the form from the WriteEmail.aspx page, it would be a PostBack; as it is, it's just a Post.
You might find this MSDN reference to be useful:
http://msdn.microsoft.com/en-us/library/ms178141.aspx

Categories

Resources