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.
Related
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.
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.
I have 2 asp:panels. One asp:panel contains a textbox and button whose code is as follows
<asp:TextBox ID="tbGoal" runat="server" CssClass="textbox" Width="222px" Height="26px"></asp:TextBox><br />
<asp:Button ID="btnUpdate" runat="server" Text="Update Goal" CssClass="button" OnClick="btnUpdate_Click" />
/* ****************************************************************************
* CODE BEHIND
*
******************************************************************************** */
protected void btnUpdate_Click(object sender, EventArgs e)
{
// I am trying to pass the updated textbox value to a label which is inside a GridView
// which is inside the second ASP:PANEL
}
Can someone tell me if this is possible. Appreciate it
First, Identify the row the label will be located.
second, determine if the label can be found FindControl method of the grid views selected row.
Once the control has been found, set the value.
the following is only a sample and may not be exact.
Label l = (Label)gv.rows[0].FindControl["label"] //again determine the index.
if (l != null)
l.text = textbox.Text
Alternative:
Change the dataset that is binding to the Gridview rather than modifying the grids values. ultimately these values will most likely have to be saved/stored anyway so do it first.
im using a ComboBox for a feature in my application, and i have AutoCompleteMode="Suggest".
However, after i type in the textbox for a search, i need to press ENTER twice to postback and show some results. This is the default behavior, like its shown in the oficial demonstration.
In my opinion, its kinda annoying and not intuitive...
Anyone have a clue how to avoid this behavior, and press just one time?
Thanks in advance
I faced the same problem and solved it:
You must set autopostback property to "false" if you dont want button to be clicked twice.
Change the AutoPostback attribute of the control to true. This will trap the tab key, which works because the control loses focus.
I doubt there is a good way to trap the enter key for this, unless you're up for breaking open the source code and performing some modifications.
<ajaxToolkit:ComboBox ID="ComboBox1" runat="server"
AutoPostBack="True"
DropDownStyle="DropDownList"
AutoCompleteMode="SuggestAppend"
CaseSensitive="False"
CssClass=""
ItemInsertLocation="Append" ... >
Tom, Jan is right and it happened to me before. you just need to set you autopostback to false. So, probably you need to set the ComboBox autopostback to false.
I managed to solve this problem with the code below:
In your aspx file, the combobox control will be:
<ajaxToolkit:ComboBox ID="cbCountries" CssClass="AquaStyle2" runat="server" AutoPostBack="true" DropDownStyle="DropDownList"
AutoCompleteMode="SuggestAppend" CaseSensitive="False" ItemInsertLocation="Append" onkeydown="FireEnterKey(this, event)" />
Then, add a reference to a javascript file, and add there the following function:
function FireEnterKey(elem, evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode != 13)
return;
var belem = $get(elem.attributes.id.value + "_Button"); //ctl00_ContentPlaceHolder1_cbCountries_Button
var telem = $get(elem.attributes.id.value + "_TextBox"); //ctl00_ContentPlaceHolder1_cbCountries_TextBox
if (navigator.userAgent.search("Firefox") >= 0) {
elem.onchange();
}
else if (navigator.userAgent.search("MSIE") >= 0) {
elem.onchange();
telem.blur();
}
else { // Opera, Safari, Chrome
telem.blur();
}
}
I hope my code above answers your question.