I have a textbox and a button on the ascx page.
After entering text i click on the button where it will post to the database and clear the textbox.
After positing, if i refresh the web page it is going to the button click method and posting the old text to the database. how can i clear the textbox value from the view state.
i have set the enableviewstate of the textbox to false. But still it is not working. Please let me know. Thanks
protected void Button_Click(object sender, EventArgs e)
{
var txt=textBox1.Text;
textBox1.Text="";//Set it to empty
// do other stuff
............
............
}
protected void btnClear_Click(object sender, EventArgs e)
{
ClearControls();
}
private void ClearControls()
{
foreach (Control c in Page.Controls)
{
foreach (Control ctrl in c.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Text = string.Empty;
}
}
}
}
After you save your data with the click button you can set the textbox.text = ""
EDIT: After your comment that textbox.text = "" is not working....
When you hit the refresh it sounds like it is resubmitting your work again. Try just reloading the page by browsing to your page again.
Also be sure to check that you aren't saving your data on every postback but just on the button click event.
Do you have any code in your page load event?
Long shot here, but this worked in my case:
TextBox.Attributes.Remove("value");
This was on a textbox with the text mode sent to 'Password'.
just add this at the end of the event after page i going o be refresh
Response.Redirect("Registration.aspx");
here my WebForm name is "Registration.aspx" instead of this put your WebForm name.
Related
First the page loads and shows an empty textbox and a button "GO"
Upon clicking the button "GO" a radioButtonList already in the page is loaded from a table based on the text in the textbox.
The radioButtonList is shown with new button "Made my choice".
The user chooses a button and clicks "Made my choice".
Upon checking for selected value or index the radiobuttonList is not checked at all...
That is it
TVM
Ricardo Conte
If you are not using Page.IspostBack property into your Page_Load then Try to use it
if(!Page.IsPostBack)
{
// Your Code..
}
into your Page_Load.Check MSDN
Hope it works for you.
protected void Page_Load(object sender, EventArgs e)
{
// Your code execute always
if(!Page.IsPostBack)
{
// Code which is execute without postback
}
}
I am very surprised to see last night my code was working fine and the next day suddenly my textbox.text always have empty string..
My code is:
Name of Event* :
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Code behind:
protected void Page_Load(object sender, EventArgs e) {
}
protected void create_Click(object sender, EventArgs e) {
if (!object.Equals(Session["UserLoginId"], null)) {
int mid = 0;
int cid = 0;
bool valid = true;
if (this.TextBox1.Text == "") {
error.Text = "<p style='color:red'>Marked Fields are compulsory!!</p>";
}
else {
.... // database insert ....
}
I am always ending up with an error.text value.
Why?
Had a similar problem with text boxes getting cleared on adding a new row. It was the issue of the page reloading when the add button was clicked.
Fixed the issue by adding:
Sub Page_Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Per Microsoft's documentation http://msdn.microsoft.com/en-us/library/aa478966.aspx.
Kinda mentioned but you should make sure your checking your that Post_Back event is not clearing your textbox. It would by default.
Try something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (this.TextBox1.Text == "")
{
error.Text = "<p style='color:red'>Marked Fields are compulsory!!</p>";
}
else
{
//.....
}
}
}
I had a similar problem. I had a textarea feeding data to a database on postback. I also designed the page to populate the textarea from the same database field. The reason it failed was because I forgot to put my reload logic inside an if(!IsPostPack) {} block. When a post back occurs the page load event gets fired again and my reload logic blanked the textarea before I could record the initial value.
If the page make a post back, then all the data , the user entered ,will be erased,as the controls are stateless, so u should keep your data entry through EnableViewState = true.
I am having this issue, but i'm using Telerik Ajax request with target in javascript. I have a RadTextBox and a RadButton. I call the same code from both of them but if i call it from the textBox and request a postback, the textbox is empty in the page load. So i call RadAjaxManager.ajaxRequestWithTarget('someUserControlClientID', 'myTextBoxText');
So in the page_load, i can grab the text, in case it's not sent to the server with the arguments sent, Request.Form("__EVENTARGUMENT") will hold my textBox value.
by the way, RadAjaxManager.ajaxRequestWithTarget is like __doPostBack('targetID', 'arguments');. Hope this helps someone. I don't have time to investigate why i lose the text with this request, so this is the workaround i did.
I have a PlaceHolder control inside of a ListView that I am using to render controls from my code behind. The code below adds the controls:
TextBox tb = new TextBox();
tb.Text = quest.Value;
tb.ID = quest.ShortName.Replace(" ", "");
((PlaceHolder)e.Item.FindControl("ph_QuestionInput")).Controls.Add(tb);
I am using the following code to retrieve the values that have been entered into the TextBox:
foreach (ListViewDataItem di in lv_Questions.Items)
{
int QuestionId = Convert.ToInt32(((HiddenField)di.FindControl("hf_QuestionId")).Value);
Question quest = dc.Questions.Single(q => q.QuestionId == QuestionId);
TextBox tb = ((TextBox)di.FindControl(quest.ShortName.Replace(" ","")));
//tb is always null!
}
But it never finds the control. I've looked at the source code for the page and the control i want has the id:
ctl00_cphContentMiddle_lv_Questions_ctrl0_Numberofacres
For some reason when I look at the controls in the ListViewDataItem it has the ClientID:
ctl00_cphContentMiddle_lv_Questions_ctrl0_ctl00
Why would it be changing Numberofacres to ctl00? Is there any way to work around this?
UPDATE:
Just to clarify, I am databinding my ListView in the Page_Init event. I then create the controls in the ItemBound event for my ListView. But based on what #Womp and MSDN are saying the controls won't actually be created until after the Load event (which is after the Page_Init event) and therefore are not in ViewState? Does this sound correct?
If so am I just SOL when it comes to retrieving the values in my dynamic controls from my OnClick event?
UPDATE 2:
So i changed the code i had in my Page_Init event from:
protected void Page_Init(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//databind lv_Questions
}
}
to:
protected void Page_Init(object sender, EventArgs e)
{
//databind lv_Questions
}
And it fixed my problem. Still a little confused as to why I want to databind regardless of whether it's a postback or not but the issue is resolved.
It looks like you're adding your textbox to a Placeholder control... but then you're searching a ListViewDataItem container for it later.
Seems to me that you need to search for the Placeholder first, and then search it for the textbox.
I am trying to set the focus to the user name TextBox which is inside an ASP.NET Login control.
I have tried to do this a couple of ways but none seem to be working. The page is loading but not going to the control.
Here is the code I've tried.
SetFocus(this.loginForm.FindControl("UserName"));
And
TextBox tbox = (TextBox)this.loginForm.FindControl("UserName");
if (tbox != null)
{
tbox.Focus();
} // if
I'm using Page.Form.DefaultFocus and it works:
// inside page_load, LoginUser is the Login control
Page.Form.DefaultFocus = LoginUser.FindControl("Username").ClientID;
Are you using a ScriptManager on the Page? If so, try the following:
public void SetInputFocus()
{
TextBox tbox = this.loginForm.FindControl("UserName") as TextBox;
if (tbox != null)
{
ScriptManager.GetCurrent(this.Page).SetFocus(tbox);
}
}
Update: Never used a multiview before, but try this:
protected void MultiView1_ActiveViewChanged(object sender, EventArgs e)
{
SetInputFocus();
}
protected void Page_Load(object sender, EventArgs e)
{
SetFocus(LoginCntl.FindControl("UserName"));
}
You may try to do the following:
-Register two scripts (one to create a function to focus on your texbox when page is displayed, second to register id of the textbox)
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "on_load",
"<script>function window_onload() \n { \n if (typeof(idLoginTextBox) == \"undefined\" || idLoginTextBox == null) \n return; \n idLoginTextBox.focus();\n } \n window.onload = window_onload; </script>");
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Focus", String.Format("<script>var idLoginTextBox=document.getElementById(\"{0}\").focus();</script>", this.loginForm.ClientID));
As the result you should get the following in your code:
<script>
function window_onload()
{
if (typeof(idLoginTextBox) == "undefined" || idLoginTextBox == null)
return;
idLoginTextBox.focus();
}
window.onload = window_onload;
</script>
<script>
var idLoginTextBox=document.getElementById("ctl00_LoginTextBox").focus();
</script>
I've been struggling with this too and I've found a solution that seems to work very well even with deeply nested controls (like AspDotNetStorefront a.k.a. ASPDNSF uses). Note the following code called from the Page_PreRender routine. I knew the name of the TextBox I wanted to give focus to and so I just called FocusNestedControl(Me, "UserName"). I just used Me here because all the routine needs is a parent of the control to get focus; it doesn't matter which parent.
Public Function FocusNestedControl(ByVal ParentControl As Control, ByVal ControlNameToFocus As String) As Control
If ParentControl.HasControls Then
For Each childCtrl As Control In ParentControl.Controls
Dim goodCtrl As Control = FocusNestedControl(childCtrl, ControlNameToFocus)
If goodCtrl IsNot Nothing Then
goodCtrl.Focus()
Return goodCtrl
End If
Next
Else
If ParentControl.ID = ControlNameToFocus Then
ParentControl.Focus()
Return ParentControl
End If
End If
Return Nothing
End Function
You can set focus directly on LoginControl and it will automatically set focus on first field in control. In your case:
this.loginForm.Focus();
More info on MSDN: How to: Set Focus on ASP.NET Web Server Controls
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
Login.FindControl("UserName").Focus();
}
My problem arrized when i moved login control to a custom control and tried to find UsernameTextBox at the OnInit() method.
OnInit of a control is executed before OnInit of Page and this is why no Form control have been created.
I moved the call to UsernameTextBox to the OnLoad function and it worked correctly.
None of the above answers worked for me, so I simply tried:
protected void Page_Load(object sender, EventArgs e) {
// This works for me
TxtMyTextBoxName.Focus();
}
... and it worked!
With an ASP TextBox defined as:
<asp:TextBox ID="TxtMyTextBoxName" type="search" runat="server"></asp:TextBox>
You must put your textbox inside this code on ASP.NET
<form id="WHATEVERYOUWANT" runat="server" method="post">
<div>
<!-- Put your code here-->
</div>
</form>
I have a user control, which is added to another user control. The nested user control is built up of a GridView, an image button and a link button. The nested user control is added to the outer control as a collection object based upon the results bound to the GridView.
The problem that I have is that my link button doesn't work. I click on it and the event doesn't fire. Even adding a break point was not reached. As the nested user control is added a number of times, I have set image button to have unique ids and also the link button. Whilst image button works correctly with its JavaScript. The link button needs to fire an event in the code behind, but despite all my efforts, I can't make it work. I am adding the link button to the control dynamically. Below is the relevant code that I am using:
public partial class ucCustomerDetails : System.Web.UI.UserControl
{
public event EventHandler ViewAllClicked;
protected override void CreateChildControls( )
{
base.CreateChildControls( );
string strUniqueID = lnkShowAllCust.UniqueID;
strUniqueID = strUniqueID.Replace('$','_');
this.lnkShowAllCust.ID = strUniqueID;
this.lnkShowAllCust.Click += new EventHandler(this.lnkShowAllCust_Click);
this.Controls.Add(lnkShowAllCust);
}
protected override void OnInit (EventArgs e)
{
CreateChildControls( );
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
base.EnsureChildControls( );
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
CreateChildControls( );
}
}
protected void lnkShowAllCust_Click(object sender, EventArgs e)
{
this.OnCustShowAllClicked(new EventArgs ( ));
}
protected virtual void OnCustShowAllClicked(EventArgs args)
{
if (this.ViewAllClicked != null)
{
this.ViewAllClicked(this, args);
}
}
}
I have been stuggling with this problem for the last 3 days and have had no success with it, and I really do need some help.
Can anyone please help me?
My LinkButton wasn't firing it's Click event, and the reason was I had its CausesValidation property set to True. If you don't want the link to validate the form, be sure to set this to False.
Try adding your click event to the linkbutton tag:
<asp:LinkButton runat="server" OnClick="linkShowAllCust_Click" />
Or adding it to your Page_Load:
Page_Load(object sender, EventArgs e)
{
this.lnkShowAllCust.Click += new EventHandler(this.lnkShowAllCust_Click);
}
Is the usercontrol within the gridview? If so register the event handler on the gridview's onrowcreated event.
It appears that you have a viewstate issue. Because the control isn't there when the viewstate is loaded the application doesn't know how to hook up the event to be fired. Here is how to work around this.
You can actually make your app work like normal by loading the control tree right after the loadviewstateevent is fired. if you override the loadviewstate event, call mybase.loadviewstate and then put your own code to regenerate the controls right after it, the values for those controls will be available on page load. In one of my apps I use a viewstate field to hold the ID or the array info that can be used to recreate those controls.
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(savedState)
If IsPostBack Then
CreateMyControls()
End If
End Sub
I had the same issue. I had viewstate="false" on the page I was adding the control to. (on the aspx page)