asp.net Validations Not working with confirmation box - c#

I want to add a confirmation box.
The following code shows the yes / no confirm box, but this does not take care of validation.
If I have made the company name field compulsory, it enters a record, even when I have not entered the company name.
I have called this method in pageload event:
CreateConfirmBox(btnAddEnquiry, "Do You Really Want to Add ?");
Method definitions:
public void CreateConfirmBox(System.Web.UI.WebControls.Button btn, string strMessage)
{
btn.Attributes.Add("OnClick", "return confirm('" + strMessage + "');");
}
aspx file
<asp:Button ID="btnAddEnquiry" runat="server"
BackColor="#0000FF"
ForeColor="LightSlateGray"
OnClick="btnAddEnquiry_Click"
Text="Add Enquiry" Width="154px" />

You are not handling any validations in your code.
I strongly suggest you to use the .NET Validation controls. They are good and barely have to write any code.
More info here;
http://msdn.microsoft.com/en-us/library/bwd43d0x%28v=vs.100%29.aspx
Code Example;
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator IdD="RequiredFieldValidator2"
ControlToValidate="TextBox1"
Display="Static"
Width="100%" runat="server">
*
</asp:RequiredFieldValidator>
<asp:Button ID="btn_Save"
Text="Validate"
OnClick="btnSave_Click"
runat="server" />
If you don't want to implement validators and use only a confirm box and thus keeping the same functionality that you currently have, you can do so by using the OnCientClick of the button which will stop the PostBack if the user clicks No.
<asp:Button ID="btnAddEnquiry" runat="server"
BackColor="#0000FF"
ForeColor="LightSlateGray"
OnClick="btnAddEnquiry_Click"
OnClientClient="javascript: return confirm('Do You Really Want to Add ?');"
Text="Add Enquiry" Width="154px" />

Related

How to execute event when user presses return on web page

I have an ASP.NET website and I have a forgot password page where the user enters their email address in a text box and when they click the button to retrieve password, the event runs as fine.
Only problem is if the user types in their email address and presses ENTER instead, it runs a search (I have a search bar at the top of the page) and so the result comes back as 'search query not found'. But this search bar at the top is on a different ASP.NET page.
So anyway, I want the event onclick to run when the user presses enter and not run a search query. Does anyone have any ideas? I've searched on this site but not really found the answer I need.
There are couple ways you can do this. If it is a webform and you have your textbox wrapped with an asp:panel you can do as below:
<asp:Panel ID="p" runat="server" DefaultButton="myButton">
<%-- Text boxes here --%>
<asp:Button ID="myButton" runat="server" />
</asp:Panel>
If its not a webform or you want to move away from that try below:
<asp:TextBox ID="TextBox1" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />
function EnterEvent(e) {
if (e.keyCode == 13) {
__doPostBack('<%=Button1.UniqueId%>', "");
}
}
And in the codebehind fire your button click in the page load based on the parameters of the postback.
Specify the "defaultbutton" property to the ID of (event you want to fire).
You can specify the "defaultbutton" property at the Form level (in the form tag)
Or else you can define them at panel level in the tag.
The form level setting is overridden at the panel level setting.
The Event Handler for the specified button gets fired simulating a true submit button functionality.
<form id="sampleform" runat="server" defaultbutton="button1">
<div>
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
<asp:Button ID="button2" runat="server" Text="Cancel" OnClick="Button2_Click" />
<asp:Button ID="button1" runat="server" Text="Ok" OnClick="button1_Click" />
<asp:Panel ID="panel1" runat="server" defaultbutton="Button5">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
<asp:Button ID="Button5" runat="server" Text="Button5" OnClick="Button5_Click" />
</asp:Panel>
</div>
</form>
In this example, Button1 is the default button for the form (Type something in Textbox 1 and hit enter, button1_Click gets fired). But for "Panel 1", default button will be Button 5 (Type in Textbox3 or Textbox 5 and hit enter).
You can have any number of panels with different default button for each panel.
Adding an ASP Panel around the text box and button with the id of the button name as the property for DefaultButton was the best way to do this.
<asp:Panel ID="p" runat="server" DefaultButton="myButton">
<%-- Text boxes here --%>
<asp:Button ID="myButton" runat="server" />
</asp:Panel>

Tries to validate when pressing logout button instead of submit

On my admin pages I've got a "Log out" button. On one page there's this form you can fill in and submit and it has some validator controls. The problem is that when I am on this page, I can't log out, because it wants the textboxes to be filled in, even though it's - obviously - not submitted via the log out button. Are the validators executing everytime you try to leave this page, even though I'm not trying to submit a form? To be clear: it works for every other page, it's just the validation here that stops it.
Form code:
<p>
<asp:Label ID="lblA" runat="server" Text="LabelA"></asp:Label><br />
<asp:TextBox ID="txtA" runat="server"></asp:TextBox>
*
<asp:RequiredFieldValidator
ID="rfvA"
runat="server"
ControlToValidate="txtA"
ErrorMessage="Required"
Display="Dynamic">
</asp:RequiredFieldValidator>
</p>
<p>
<asp:Label ID="lblB" runat="server" Text="LabelB"></asp:Label><br />
<asp:TextBox ID="txtB" runat="server"></asp:TextBox>
*
<asp:RequiredFieldValidator
ID="rfvB"
runat="server"
ControlToValidate="txtB"
ErrorMessage="Required"
Display="Dynamic">
</asp:RequiredFieldValidator>
</p>
Logout button:
<asp:Button runat="server" Text="Log out" ID="btnLogout" OnClick="btnLogout_Click"/>
When Log out is clicked:
protected void btnLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
Any ideas?
add cause validation false to your button
<asp:Button runat="server" CausesValidation="False" Text="Log out" ID="btnLogout" OnClick="btnLogout_Click"/>
Also you can use the ValidationGroup property of the controls.
Assign the same ValidationGroup to the group of controls(and RequiredFieldValidator) which you require for validation like username and password text boxes and login button(In your case to the two text boxes) and assign the different ValidationGroup to the other controls(In your case to logout button).
So the validation fires only when the same validation group's button has been clicked.

Validation control not firing on form submit

I'm using a FormView control to allow users to insert rows to the database. I want to validate these input fields, and as such have added a regular expression validation helper. Here's the markup:
<InsertItemTemplate>
<p>
Name:
<asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
<asp:RegularExpressionValidator ValidationExpression="^[a-zA-Z0-9 ]*$" ControlToValidate="NameTextBox" ID="NameTextBoxValidator" runat="server" ErrorMessage="Must be alphanumeric characters and spaces"></asp:RegularExpressionValidator>
</p>
<p>
Location:
<asp:TextBox ID="LocationTextBox" runat="server"
Text='<%# Bind("Location") %>' />
</p>
<p>
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
</p>
</InsertItemTemplate>
However, when I click InsertButton the page refreshes and I get an error from SQL Server saying it can't insert a NULL value, the validator isn't getting used at all.
How can I fix this?
I assume that the user entered no text and the database does not allow null values.
A RegularExpressionValidator will not validate empty controls. So you need to provide also a RequiredFieldValidator.
The validation will not fail if the input control is empty. Use the
RequiredFieldValidator control to make the field required.
http://www.w3schools.com/aspnet/control_regularexpvalidator.asp
Not much info here, but I'll venture a guess:
Check to make sure you don't have anything happening OnLoad that's blanking things out. If you do have an OnLoad make sure it only fires when IsPostback is false.

Validate dropdown from custom control in page

I have a custom control included in a form that includes a dropdown list. The form has a number of other required fields, so i was wondering how to validate this dropdown.
<gaia:TextBox ID="TitleTextBox" runat="server"/>
<gaia:RequiredFieldValidator runat="server" ControlToValidate="TitleTextBox"
ErrorMessage="Please fill in the press release title" Text="*" Display="None" ValidationGroup="save" />
<CN:ProductCategoryDropDown runat="server" ID="ProductCategoryDropDown" />
<gaia:CustomValidator runat="server" ID="ProductCategoryValidator" OnServerValidate="ProductCategory_Validate" ValidationGroup="save"
Display="None" Text="*" ErrorMessage="Please select a category" />
the code behind looks like this
protected void ProductCategory_Validate(object source, ServerValidateEventArgs args)
{
args.IsValid = (ProductCategoryDropDown.SelectedValue>0);
}
On the customvalidator above, I purposely left out the 'ControlToValidate' because it throws an error.
Please help.
The easiest would be to include the CustomValidator in the UserControl.
Then you could provide a property for the Validation-Group and another ValidatorEnabled to set the validator group and enable/disable the validator.

Setting focus to a button from text box?

I have a few text boxes and buttons on my form.
Lets say txtBox1 is next to btnSubmit1,
txtBox2 is next to btnSubmit2,
txtBox3 is next to btnSubmit3.
How can I set the focus on btnSubmit3 when the user starts to type something in txtBox3.
Meaning..... if a user type in a text box the program will know what button to fire when the user press the enter key.
If you use a panel, you should be able to set a defaultbutton. I´m not sure if it´s an win forms application or a web forms application, but this is how you should do it with web forms:
<asp:Panel id="panel1" runat="server" DefaultButton="Button1">
<asp:TextBox id="textbox1" runat="server" />
<asp:Button id="Button1" runat="server" Text="Button 1" />
</asp:Panel>
<asp:Panel id="panel2" runat="server" DefaultButton="Button2">
<asp:TextBox id="textbox2" runat="server" />
<asp:Button id="Button2" runat="server" Text="Button 2" />
</asp:Panel>
<asp:Panel id="panel3" runat="server" DefaultButton="Button3">
<asp:TextBox id="textbox3" runat="server" />
<asp:Button id="Button3" runat="server" Text="Button 3" />
</asp:Panel>
Use JavaScript and add a "onblur" for those TextBoxes...
Example:
<asp:TextBox ID="t1" runat="server" onblur="CheckIfTextBox1ShouldFocusOnButton1();" />
:)
I've seen it done like this but don't ask me to explain it or to say what the pros and cons are over any other method. Just thought I would publish it in case its useful to you.
// Fires a particular event when enter is pressed within a textbox.
function FireButtonOnEnter(controlID)
{
if((event.which ? event.which : event.keyCode) == 13)
{
window.event.returnValue = false;
window.event.cancelBubble = true;
document.getElementById(controlID).click();
}
}
Call it by adding the following for the textbox...
txtOrgName.Attributes.Add("OnKeyDown", String.Format("return FireButtonOnEnter('{0}');", btnOrgNameGo.ID));
This is an easy solution if you know that the only browser being used is IE.
You just have to add to the Page load
txtBox1.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13)
__doPostBack('" + btnSubmit1.UniqueID + "','')");
txtBox2.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13)
__doPostBack('" + btnSubmit2.UniqueID + "','')");
txtBox3.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13)
__doPostBack('" + btnSubmit3.UniqueID + "','')");
The reason that this only works in IE is that it uses the Javascript "event" key word that doesn't work in Firefox.

Categories