Autopostback prevents button click - c#

I have an asp.net page and on it there are a number of controls, including:
A textbox with autopostback = true and the server side textchanged event implemented
A button with the server side click event implemented
The textbox performs the postback as soon as the user leaves the control (ie, focus is lost). The problem is that if the user happens to change the value and then press the button without leaving the textbox, then on button click the textbox will perform the postback but the button click will be lost.
How can i force both the textbox and the button events to fire consecutively in such cases?
Thanks

Try:
ASPX:
<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />
JS:
function EnterEvent(e) {
if (e.keyCode == 13) {
__doPostBack('<%=Button1.UniqueId%>', "");
}
}
CS:
protected void Button1_Click1(object sender, EventArgs e)
{
}

You can delay postback from textbox and cancel it in case of button click. To do this add code below to Page_PreRender method:
protected void Page_PreRender(object sender, EventArgs e)
{
Button1.OnClientClick = string.Format("if(window.{0}Timeout){{ clearTimeout(window.{0}Timeout); }}",
TextBox1.ClientID);
TextBox1.Attributes["onChange"] = string.Format("javascript:window.{0}Timeout = setTimeout(\"{1}\", 500); return;",
TextBox1.ClientID,
ClientScript.GetPostBackEventReference(TextBox1, ""));
}

Related

CustomValidator firing but not not preventing postback in ASP.NET

I am using a CustomValidator in ASP.NET as follows.
<asp:CustomValidator ID="AnswerCV" runat="server" ForeColor="Red"
ValidateEmptyText="True" ValidationGroup="test"
OnServerValidate="CustomValidation" ControlToValidate="TextBox1" Enabled="True"
ErrorMessage="You must fill in the text box.">
</asp:CustomValidator>
<asp:TextBox ID="TextBox1" ValidationGroup="test" runat="server">
</asp:TextBox>
<asp:Button runat="server" Id="Button" CausesValidation="True" ValidationGroup="test"
OnClick="Button_Click" />
In the code behind I have
protected void CustomValidation(object sender, ServerValidateEventArgs e)
{
MessageBox.Show("It is firing!!!");
if (string.IsNullOrEmpty(TextBox1.Text))
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}
}
And the button click method is as follows
protected void Button_Click(object sender, EventArgs e)
{
MessageBox.Show("I should not have fired.");
}
The CustomValidation method fires but the Button_Click method fires after that and then the "You must fill in the text box." error message displays. How do I prevent the Button_Click method from firing, when the text box is empty the validation is failing and triggering the error message, but after the Button_click method has fired?
The stackoverflow page here offered other solutions which I have implemented but still the Button_Click method fires.
Aside: And the client side solutions I can not use as I am dynamically going to add code in the Init() method that enables and disables the CustomValidator via a CheckedChanged event in only certain Radio Buttons. End Of Aside
I have also tried the CustomValidator without the OnServerValidate method and I have tried returning a boolean of false from the CustomValidation method cause a syntax error.
protected void Button_Click(object sender, EventArgs e)
{
if (IsValid)
{
Response.Write(" alert ('I should not have fired'); ");
}
}
Please add one if condition in Button_Click Event
protected void Button_Click(object sender, EventArgs e)
{
if (IsValid)
{
Response.Write("<script> alert ('I should not have fired');
</script>");
}
}

In aspx how to trigger button click event when press "Enter" on a textbox while the button click event defined in source cs file

While, I want to trigger btnSearchSuiteGroup_Click event when pressing "enter" on txtSuiteGroupName which described in aspx, code below:
<asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass="DD" onkeypress="return searchKeyPress(event)"></asp:TextBox>
<asp:Button ID="btnSearchSuiteGroup" runat="server" Text="Search" CssClass="DD" Width="64px" onclick="btnSearchSuiteGroup_Click" />
<script type="text/javascript">
function searchKeyPress(e) {
// look for window.event in case event isn't passed in
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById('<%=btnSearchSuiteGroup.ClientID%>').click();
}
}
</script>
While, the btnSearchSuiteGroup_Click is defined in the source cs file:
protected void btnSearchSuiteGroup_Click(object sender, EventArgs e)
{
this.LinqDataSource1.WhereParameters["SuiteGroupName"].DefaultValue = this.txtSuiteGroupName.Text;
this.GridView1.DataBind();
if (GridView1.Rows.Count == 0)
Response.Write("<script language='javascript'>window.alert('No record found!')</script>");
}
When I browse the website, the keypress on the textbox cannot initiate the button click event, anything wrong in the code?
If you use Panel you would not need to use any javascript function. You can specify default button Id for panel like below
<asp:Panel runat="server" DefaultButton="btnSearchSuiteGroup">
<asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass="DD">
</asp:TextBox>
<asp:Button ID="btnSearchSuiteGroup" runat="server" Text="Search" CssClass="DD" Width="64px" onclick="btnSearchSuiteGroup_Click" />
</asp:Button>
</asp:Panel>
OfCourse you can have Multiple panels on single page for assigning different default buttons for separate panels!
For More On Panel.DefaultButton Property
I suggest the following method:
1. Create a function 'ButtonClick' and put all the code in 'btnSearchSuiteGroup_Click' function into it.
2. Add 'onkeypress' event for the textbox 'txtSuiteGroupName' by looking at this thread
3. Whenever the above event is fired, see if the entered key is 'Enter'.
4. If the key is 'Enter' key, call the function 'ButtonClick'.

How to force enable/disable of controls in aspx?

I have a simple windows form app which I have to migrate to run on a webpage, so I'm trying with aspx(c#).
I have two radio buttons, but at time only one of them should be checked. I implemented the very same code from the original app, but it's not working:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked == true)
{
RadioButton2.Checked = false;
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked == true)
{
RadioButton1.Checked = false;
}
}
So why these changes not being applied on the page?
you can use GroupName Property of RadioButton Control.
if you set the same GroupName for set of RadioButtons you don't need to write the Code Behid which you have written in the above Post/Question, as only one radio button can be selected from the group.
but if you want to invoke some action like Disabling TextBox on Particular Radio Button click event you can use following sample code.
Example: in this example i'm taking 3 Radio Buttons all set to Same GroupName, hence only one RadioButton canbe selected at a time.
when user selects/checks a RadioButton1 i'm Disabling the TextBox1.
Note : Please Make sure that your RadioButton AutoPostBack Property set to True otherwise events on RadioButton won't be fired.
Design Code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RadioButton ID="RadioButton1" runat="server" Text="DisableTextBox" GroupName="Group1" AutoPostBack="True" OnCheckedChanged="RadioButton1_CheckedChanged"/>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Group1" AutoPostBack="True"/>
<asp:RadioButton ID="RadioButton3" runat="server" GroupName="Group1" AutoPostBack="True" />
Code Behind:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
TextBox3.Enabled = false;
else
TextBox3.Enabled = true;
}
Put the checkboxes in a GroubBox or Panel
You can set the GroupName of both radiobuttons the same, so the Code Behind you wrote is not needed anymore.
Also, check out the RadioButtonList
UPDATE
Your aspx-code should look something like this:
<asp:RadioButton id="RadioButtonEnabled" runat="server" Text="Enabled" GroupName="GroupTxtEnabled" AutoPostBack="True" OnCheckedChanged="RadioButtonEnabled_CheckedChanged"/>
<asp:RadioButton id="RadioButtonDisabled" runat="server" Text="Disabled" GroupName="GroupTxtEnabled" AutoPostBack="True"/>
<asp:TextBox id="TextBox1" runat="server"/>
And in your code-behind:
protected void RadioButtonEnabled_CheckedChanged (object sender, EventArgs e)
{
TextBox1 = RadioButtonEnabled.Checked
}
As you can see, I've used the OnCheckedChanged only at one radiobutton, since both radiobuttons are changed at the same time (property GroupName is equal).

Using OnClick event with PostBackUrl attribute of asp:Button

I have an asp:Button control like this;
<asp:Button ID="btnPayCC" CssClass="paymentButton" runat="server" Text="ONAYLA"
OnClientClick="if(!doPostBack()) return false; frmMaster.target='_blank'"
PostBackUrl="http://www.google.com" OnClick="btnPayCC_Click" />
And doPostBack javascript function is;
function doPostBack()
{
__doPostBack('<%= btnPayCC.ClientID %>', '');
return true;
};
When I clicked the button, then it opens new page(google.com) as I wish,
But do not postback into button control's OnClick event.
What is the problem?
How can I solve it?
I had the same problem. I solved it by adding a Response.Redirect("url") at the end of my onClick event for the Button and removing the PostbackUrl attribute from the button so that is uses autopostback to the same url. IE:
protected void Button_Click(object sender, EventArgs e)
{
//do your button click events here
Response.Redirect("~/url.aspx");
}
and
<asp:Button ID="Button" runat="server" CausesValidation="false" OnClick="Button_Click">

How to validate a form in ASP.NET using an image button, before raising the onClick event?

This may be a silly question but i'm a beginer here..
I created a form in asp.net and it's all fields are validated using validation controls on clicking an image button.It is working properly.After that i add an event to the button.This is the code of that button.
<asp:ImageButton ID="Submit" runat="server" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" OnClientClick="submitClicked" />
The purpose of that event is for submitting all the values in the form to database.Here my problem is,After adding the onClick event to button, validation has not taken place.And i want these onClick event to raise only when the form is validated successfully.Can any one guide me ..Thanks in Advance.
make sure that you are using the same validation group for all the validation controls.
in addition you can use OnClientClick event to call validation.
<asp:ImageButton ID="Submit" runat="server" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" OnClientClick="return Page_ClientValidate('AddSchoolValidationGroup');" />
You need to validate the page before submitting. Please add attribute for button.
protected void Page_Load(object sender, EventArgs e)
{
Submit.Attributes.Add("onclick", "javascript:if(Page_ClientValidate('AddSchoolValidationGroup')){return true;}else{return false;}");
}
Since you have a method "submitClicked" in onclient click, you can call the same inside Page_ClientValidate and remove the existing "OnClientClick" property.
protected void Page_Load(object sender, EventArgs e)
{
Submit.Attributes.Add("onclick", "javascript:if(Page_ClientValidate('AddSchoolValidationGroup')){submitClicked(); return true;}else{return false;}");
}
You can use javascript function
function validateForm() {
if (document.getElementById('txtName').value == '')
{
ValidatorEnable(document.getElementById("rfvName"), true) // rfvName is id of validator
return false; }
}
and call that function on client click of image button
<asp:ImageButton ID="Submit" runat="server" OnClientClick="validateForm();" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" />
Replace OnClientClick="submitClicked" with OnClientClick="return submitClicked();"
function submitClicked()
{
if (document.getElementById('txtname') != '') {
return true;
}
else {
alert('Please Enter Name');
return false;
}
}
So until all the validations are validated, the Server side event will not be called.

Categories

Resources