My web site uses a master page, where I've placed two controls, a TextBox and an ImageButton, they are intended to be viewed and accessible on all content sites. Here's the aspx code in Site.Master:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageBtn" runat="server" ImageUrl="~/Image.png"
PostBackUrl="~/Result.aspx"></asp:ImageButton>
Clicking the button should redirect the visitor to Result.aspx, which it does.
Result.aspx.cs has the following in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
TextBox txbx = this.Master.FindControl("TextBox1") as TextBox;
if (txbx != null)
{
Label1.Text = "Value: " + txbx.Text;
}
else
{
Label1.Text = "TextBox seems to be null";
}
}
The weird behavior appears when the image button is clicked the first time. The visitor gets this information from the page "Value: " (i.e an empty string ""), even though a value was entered in TextBox1. The subsequent clicks presents the value(s) correctly, e.g "Value: SomeText".
Why doesn't the value "come along" the first time?
Is there a better way to ensure that?
The visitor is redirected to Result.aspx AND
that the value is "registered" and can be handled in Result.aspx.cs AND
that a user will be redirected, if Result.aspx is entered without the use of the image buttons PostBackURL
I've tried IsPostBack but it seems to behave strangely when using a master page as previous page ...
Very thankful for an answer!
Sincerely,
Mr Kay
If you are using PostBackURL on your ImageButton on the master page and come from another page you must use:
PreviousPage.Master.FindControl("TextBox1") as TextBox;
If you are on the PostBackURL page and click your ImageButton, you need to use
Master.FinControl("TextBox1") as TextBox;
(PreviousPage would be null in this case)
you could use something like this:
var txbx = PreviousPage == null ?
Master.FindControl("TextBox1") as TextBox :
PreviousPage.Master.FindControl("TextBox1") as TextBox;
See: http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage(v=vs.100).aspx
at the Remarks section.
Since you know your form is derived from the master... have you tried explicit type-casting to get at it??? such as
TextBox txbx = ((site.Master)this).Textbox1;
then do whatever you want from there... It's been a while since I've been into asp.net, but remember doing something similar in one of my older apps.
Related
i know there is a lot of questions similar to mine but none of them solved my problem.
The Idea:
i have two pages the first one is a login page and the other one is to show the logged in person attendance, in the attendance page i have two tabs one for the employee itself and the other one is to dynamically show the names of the employees under him, the second tab is presented as buttons that contain the employees name, and when you click it, it shows that person attendance.
The Problem:
when i click on the button it refresh the page without doing anything then when i click it again it works and calls the method i needed, so my question is why it doesn't work from the first click ?
Solution Attempt:
i created the buttons in code behind this way :
var button = new Button
{
ID = "Button " + a,
CommandArgument = myEmp[a].ToString(), //id of employee
Text = GetName(myEmp[a]), // name of employee
CausesValidation = false
};
button.Command += GetINAndOutManagers; //method on click
var cell = new HtmlTableCell();
var row = new HtmlTableRow();
cell.Controls.Add(button);
row.Cells.Add(cell);
myTable.Rows.Add(row); // just for organization i put them in a table
and in my html page :
<table id="myTable" runat="server" class="table table-bordered"></table>
as a place holder.
1- i have JavaScript and jquery in my page but even when i remove them it doesn't work.
2- i tried using html buttons instead in code behind put still don't work.
3- i tried putting it in page init and page preinit but no result.
the only time it worked when i put the buttons in the main page not the content page i don't know why, and i noticed when i click the button for the first time it doesn't consider it as a post back.
any ideas ?
EDIT
so to make it easier i deleted everything in my page load method
and in my page init method i have this code only.
protected void Page_Init(object sender, EventArgs e)
{
Button btn = new Button();
pnlInfo.Controls.Add(btn);
btn.ID = "Button" + 1.ToString();
btn.Text = "Test button" + 1.ToString();
btn.Click += new EventHandler(btnSubmit_click);
}
and the method on click is like this:
private void btnSubmit_click(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write("**************in*****************");
}
so i only login and then it will redirect me to the second page which contains one button only created as you see in my page init method, no tabs no nothing
and in my html is this
<asp:Panel ID="pnlInfo" runat="server">
</asp:Panel>
with some css and divs that's all, and it's still won't work from the first click !
Oh Gosh, i found my solution
in my login page i used this code to transfer to my second page:
Server.Transfer("About.aspx", true);
so my buttons did not work, but when i change the code to this:
Response.Redirect("About.aspx");
everything worked !
well i'm an asp.net beginner so i don't know why that solved
my problem. but thanks everyone, hope this help someone else too.
I have the following code in the code behind. Goal is to reset the value of the textbox to blank. When I click the button, however, nothing happens.
protected void btnReset_Click(object sender, EventArgs e)
{
Label srch_Title = (Label)FindControl("srch_Title");
srch_Title.Text = String.Empty;
}
Here is the textbox code from the main page:
<asp:TextBox ID="srch_Title" AutoPostBack="true" runat="server" />
Here is the button code from the main page:
<asp:Button ID="btnResetSearch" runat="server" OnClick="btnReset_Click" Height="35px" Text="Reset Search" Width="120px" />
I am a novice / enthusiast programmer and this is my first post. Guessing the problem is obvious and I am just not seeing it.
You should define your control as TextBox not Label , like this :
TextBox srch_Title = (TextBox )Form.FindControl("srch_Title");
srch_Title.Text = String.Empty;
You need to find the srch_Title control as a TextBox instead of as a Label, like this:
// The as operator avoids a cast exception,
// returns null if cast cannot be successfully performed
TextBox theSrchTitleTextBox = Form.FindControl("srch_Title") as TextBox;
// Verify that we found the text box before we try to use it,
// to avoid null reference exception
if(theSrchTitleTextBox != null)
{
theSrchTitleTextBox.Text = String.Empty;
}
Figured this out by adding another FindControl. First FindControl referred to the master and used the results of that to setup a second FindControl pointed at the text box. I did not post enough code when I asked the original question as I think an experienced programmer would have quickly spotted the solution. Thanks to all who contributed.
I have a web form that allows the user to modify data in certain fields (mostly TextBox controls, with a couple of CheckBox, DropDownList, and one RadioButtonList control) with a submit button to save the changes. Pretty standard stuff. The catch is, I need to keep track of which fields they modified. So I'm using ASP.NET HiddenField controls to store the original value and then on submit comparing that to the value of the corresponding TextBox (for example) control to determine which fields have been modified.
However, when I submit the form and do the comparison, the value of the TextBox control in the code behind still reflects the original value, even though I have changed the contents of the TextBox, so it isn't registering the change. Here is an example of a set of TextBox/HiddenField pairings (in this case last, first, middle names) in my ASP.NET form:
<div id="editName" class="editField" style="display: none">
<asp:TextBox ID="tbxLName" runat="server" class="editable"></asp:TextBox>,
<asp:TextBox ID="tbxFName" runat="server" class="editable"></asp:TextBox>
<asp:TextBox ID="tbxMName" runat="server" class="editable"></asp:TextBox>
<asp:HiddenField ID="hdnLName" runat="server" />
<asp:HiddenField ID="hdnFName" runat="server" />
<asp:HiddenField ID="hdnMName" runat="server" />
</div>
I'm setting the original values of all these controls (".Text" for the TextBox controls, ".Value" for the HiddenField controls) on PageLoad in the code behind.
Here's an example of where I'm doing the comparison when I submit the form (I'm adding the field name, old value, and new value to List<string> objects if the values differ):
if (tbxLName.Text != hdnLName.Value)
{
changes.Add("ConsumerLastName");
oldVal.Add(hdnLName.Value);
newVal.Add(tbxLName.Text);
}
But when I enter a new value into the TextBox control and click Submit:
then step through the code in the debugger, it shows me that the value of the control is still the old value:
Why is the comparison happening against the original value of the TextBox even though the new value is there when I click the submit button?
Update: #David gets the credit for this, even though he didn't post it as an answer -- I was forgetting to enclose the method for pre-filling the original values of the controls in a check for IsPostBack; I really should have known better, I've been doing this for quite a while!
Are you checking for IsPostback in Page_Load so you don't overwrite the values sent in the Postback?
Make sure that you are not overwriting your values in the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
someTextField = "Some Value";
}
}
It took a while for me to get that the Page_Load method works as an "before anything goes" method and not only a method that is being ran when you visit the page with GET.
Make sure you're not overwriting the value for the textbox somewhere in page init or load without checking for the IsPostback flag.
It may happen due to postback. If you code for set textbox not in !isPostBack then put it.
i.e.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
tbxLName.Text="anything";
}
}
I am creating a custom user control that will act as a search feature. I want to easily be able to add this to multiple pages without having to modify much code.
I thought the best method to do this would be to create a simple user control that I can inject anywhere with one line of code and then have this control postback to a different URL. So wherever the search function is, it will always post back to the same page. My control looks like this:
<asp:TextBox ID="searchTextBox" runat="server" MaxLength="350"></asp:TextBox>
<asp:Button ID="submit" runat="server" Text="Search" PostBackUrl="~/myPostBackPage.aspx" />
myPostBackPage.aspx.cs looks like this, but it isn't grabbing the text.
protected void Page_Load(object sender, EventArgs e)
{
content.InnerHtml = ((TextBox)PreviousPage.FindControl("searchTextBox")).Text;
}
But it isn't pulling anything from the searchTextBox field and I get:
Object reference not set to an instance of an object.
Is there a better way to do this or how should I fix my code? Thanks!
I don't know where the TextBox is declared, if you for example use MasterPages the NamingContainer of it would be the ContentPlaceHolder of the master instead of the Page. Therefore just cast the PreviousPage property to the correct type:
YourPageType page = PreviousPage as YourPageType;
if(page != null)
{
content.InnerHtml = page.SearchText;
}
You have to provide a public property since the TextBox is protected(best-practise anyway):
public string SearchText
{
get { return searchTextBox.Text; }
}
I tested your code and PreviousPage is null. Try switch to Page.
Obscure solution at end of post
Using asp.net page with C# codebehind, I have successfully built and populated a DropDownList.
What I would like to do is capture a new value selected from the dropdownlist (preferrably using a postback to my codebehind). The codebehind can then update other things on the page based on this newly selected dropdownlist value.
My first attempt was to use
<asp:DropDownList ID="myDDL" runat="server" AutoPostBack="true" OnSelectedIndexChanged="foo"></asp:DropDownList>
with the C# method
public void foo(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
string myValue = "";
if (ddl != null)
{
myValue = ddl.SelectedValue;
// Do some stuff
}
}
This did not work. When the selected index was changed, it simply reloaded the page, but the IsPostBack flag was always false.
So I sifted through SO and tried a number of different tactics. Most recently, I tried to register the client-side onChange event in the codebehind and turned off the AutoPostBack.
in the ASP.Net page:
<asp:DropDownList ID="myDDL" runat="server" AutoPostBack="false"></asp:DropDownList>
in the codebehind:
myDDL.Attributes.Add("onChange", "doSomeStuff(this);"); // Done on databind.
I added the client-side javascript to call the page's __doPostBack function
<script language="javascript" type="text/javascript">
function doSomeStuff(ddl) {
var ddlVals = document.getElementById(ddl.id);
__doPostBack(ddlVals, '');
}
</script>
This also failed, although I thought it was going somewhere when I saw the javascript execute properly.
Looking in the codebehind, though, it's still not working. When I put a breakpoint in the Page_Load IsPostBack is false! But it's supposed to be a postback!? It was posted back using __doPostBack and (seperately) automatically with AutoPostBack="true"
So I dug deeper.
According to this MSDN article (http://msdn.microsoft.com/en-us/library/ms178141(v=VS.85).aspx) based on the results on the page load I'm doing a "Server Transfer" rather than the desired Postback (IsPostBack is false, PreviousPage is, as expected, the same page that should be posting back, IsCallback is false, and IsCrossPagePosting is false).
What could be going on to hyjack the AutoPostBack and the __doPostBack to make it look and act like a "Server Transfer"?
What can I set/check on the parent control/page to make sure it's allowing postbacks?
EDIT:
The Page_Load looks something like:
private SpecialDataObject _someData;
private string foobar;
public void Page_Load(object sender, EventArgs e)
{
//set some variables.
this.foobar = "blah";
LoadSomeUnrelatedData();
if (!IsPostBack)
{
if (_someData == null)
{
LoadDataWithoutBinding();
}
BindMyData();
}
}
With a breakpoint at //set some variables the Page.IsPostBack is always false even after AutoPostBack.
EDIT 2:
The answer was in the Server Transfer. In a distant control loaded from the master page, the URL is inspected and rerouted before it hits the page, effectively negating my postback. I didn't see it before because I had added the breakpoints only in the target page.
I would check to make sure that you don't have validation somewhere interfering with the postback. To check this, set CausesValidation to false on the DropDownList.
Are you resetting the value of your dropdown in your PageLoad?
Also you may want to think about using an UpdatePanel so that it doesnt reload the whole page.
Is it inside an UpdatePanel? If yes, set ChildrenAsTriggers="true"
Based on the attempts you've mentioned, as well as the comments regarding the update panel, I attempted a few things.
By setting the data source on the load event, you will only do it once:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//set up data here
}
}
You may use the Page.IsPostBack code and the method of yours to get what you want:
if (Page.IsPostBack)
{
//do page reload logic in here
}
protected void foo(object sender, EventArgs e)
{
//get your selected value here
}
(Note: Both of the postback conditionals are in the page load event)
EDIT:
Here's the whole setup, its basic, but you get the idea:
As you can see when I made a selection from cat to dog, it recognized that there was a postback, so it skipped the databind and set t. I could only assume there's something else here that I'm not seeing if you can't get it to ever return true for you on postback.