Show Message Box if TextBox is Blank or Empty using C# - c#

I am trying to check first if users don not enter either User ID or Password, if either text box is blank or empty then I want to show message box, if they enter both user id and password then I want to execute some other codes. The problem I am having with the code is that the message does not show at all but the good thing is that it does not execute the other code. So I would like to see the message box to show up if both text boxes are empty. I am not sure why the message box is not showing up even though I have used this same code in other functions and it worked. thanks
here is my button code for the ASPX
<asp:Panel ID="Panel1" runat="server" BorderStyle="Groove" Height="109px" Visible="false"
Width="870px" BackColor="#FFFFE1">
<asp:Label ID="Label2" runat="server" Text="DIGITAL SIGNATURE" Font-Bold="True"
ForeColor="#FF3300"></asp:Label>
<br />
<br />
<asp:Label ID="lblUID" runat="server" Text="User ID:"></asp:Label>
<asp:TextBox ID="txtUID" runat="server" Height="22px" Width="145px"></asp:TextBox>
<asp:Label ID="lblPass" runat="server" Text="Password:"></asp:Label>
<asp:TextBox ID="txtPass" runat="server" Height="23px" TextMode="Password" style="margin-top: 0px"></asp:TextBox>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="183px"
onclick="btnSubmit_Click"
OnClientClick="return confirm('Are you sure you want to submit?');"
Font-Bold="False" Font-Size="Medium" Height="30px"
style="margin-right: 1px" />
<br />
</asp:Panel>
code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUID.Text.Length == 0 || txtPass.Text.Length == 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please type your User ID and Password correctly and click Submit button again. Thanks", true);
}
else
{
//execute some code here
}
}

In your code in btnSubmit_Click method, when you call RegisterClientScriptBlock you missed '); symbols at then end of your alert. So, your javascript is incorrect, and browser displays an error in developers tools. It should be like this:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUID.Text.Length == 0 || txtPass.Text.Length == 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please type your User ID and Password correctly and click Submit button again. Thanks');", true);
}
else
{
//execute some code here
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUID.Text.Length == 0 || txtPass.Text.Length == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertMessage", "alert('Please type your User ID and Password correctly and click Submit button again. Thanks');", true);
}
else
{
//execute some code here
}
}

One approach would be to do this client-side. You could change your OnClientClick to:
return login();
and then build the login function:
function login() {
if ($('#txtUID').val() === '' ||
$('#txtPass').val() === '') {
alert('Please type your User ID and Password correctly and click Submit button again. Thanks');
return false;
}
return confirm('Are you sure you want to submit?');
}
and so now you can get rid of the server-side code.

I have created common .js file which contains all client side validation as
function checkMandatory(ele)
{
var text;
text = ele.value;
if(text.length == 0)
{
alert("Please enter value ...");
ele.focus();
return;
}
}
Call function in Page_Load event as
txtName.Attributes.Add("onFocusout", "checkMandatory(this);");
Note: Dont forget to include .js file to your page inside HTML tags.

Related

Textbox remembers its data on page refresh

I have 2 textbox on my page and a Button. When I click on a button, the text from the textbox is emailed. But, then when i refresh the page and no content is there, then also i get an email.
protected void Button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(TextBox2.Text))
{
//email logic
TextBox1.Text = "";
TextBox2.Text = "";
}
else
{
//do nothing
}
}
Here, on clicking the button, i get an email but then when i refresh the page, even though there is no data, then also it goes inside the loop and i get an email.
How do i stop this ?
Do the following in your Page_Load event and keep your TextBoxes and Button in an <asp:UpdatePanel>. Then the page will not ask to re-submit each time you refresh the page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
}
UPDATE
Keep the controls within an UpdatePanel as follows
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Send mail" onclick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You need to use the the POST > Redirect > GET pattern. Here is explanation link

How to display confirm dialog from C# to client and use the result

I have a generic handler which deletes a file from a location after getting a confirmation from the user that is what they really want.
My code is:
public class DeleteFilePDF : IHttpHandler {
public void ProcessRequest (HttpContext context) {
System.Web.HttpRequest request2 = System.Web.HttpContext.Current.Request;
string strSessVar2 = request2.QueryString["fileVar"];
//MessageBox.Show(strSessVar2);
if (File.Exists(strSessVar2))
{
DialogResult dlgRes = MessageBox.Show("Do you really want to delete the file?", "Program Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlgRes == DialogResult.Yes)
{
try
{
File.Delete(strSessVar2);
HttpContext.Current.Response.Redirect("PDFAllFilesDisplay.aspx", false);
}
catch (Exception ce)
{
}
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
My ImageButton code:
<asp:ImageButton runat="server" ToolTip="Delete File" ID="lnkDelete" OnClick="DeleteFile" CommandArgument='<%# Container.DataItemIndex %>' ImageUrl="~/delete.png" Width="50px" Height="50px" />
My ImageButton code-behind:
protected void DeleteFile(object sender, EventArgs e)
{
string strFile = GridView1.Rows[Convert.ToInt32(((ImageButton)sender).CommandArgument.ToString())].Cells[0].Text;
string strFolderFile = strDirectory + strFile;
//MessageBox.Show(strFolderFile);
Response.Redirect("DeleteFilePDF.ashx?fileVar=" + strFolderFile);
}
Everything works as it should in debugging environment but outside of that I am not able to use MessageBox.Show() function. How can I achieve the same thing using a JQuery/JavaScript confirm dialog?
Get the confirmation from javascript and process server click
<asp:ImageButton runat="server" OnClientClick="return getConfirmation()"
ToolTip="Delete File" ID="lnkDelete" OnClick="DeleteFile"
CommandArgument='<%# Container.DataItemIndex %>'
ImageUrl="~/delete.png" Width="50px" Height="50px" />
Then JS code
function getConfirmation(){
return window.confirm("Do you really want to delete the file?");
}
There are some nice UIs available for showing a confirmation box. Check out jQuery Modal dialog or bootstrap bootbox, etc
You can't do it that way because your handler is executed on the server. Instead you will have to use JavaScript to decide whether or not to delete the file. for example:
<input type="button" onclick="deleteFile()" value="Delete File" title="Press to delete file" />
function deleteFile {
//show dialog with jquery or anything similar
//if yes is selected, then make the handler call using ajax. for example using jquery ajax:
$.ajax({ url: [handler url] + [query string], method: "post" });
}

ModalPopupExtender ASP MessageBox not closing

I wanted a popup messagebox that would show something like "Done!" when the row in my gridview is successfully removed and something else if there is an error. I used ModalPopupExtender. The modal popup shows fine but it just keeps on the page even if I click the OK button. Here is my code:
ASP:
<!--ModalPopup for "Done" message-->
<asp:ModalPopupExtender ID="ModalPopupExtDone" runat="server" PopupControlID="donePanel" TargetControlID="donePanel" CancelControlID="donePanelBtn">
</asp:ModalPopupExtender>
<div class="panel">
<asp:Panel ID="donePanel" runat="server" Width="200px" Height="41px"
BackColor="#FF9900">
<asp:Label ID="donePanelLabel" runat="server" ForeColor="#FF3300"></asp:Label>
<br />
<asp:Button ID="donePanelBtn" runat="server" Text="OK"
onclick="donePanelBtn_Click" />
</asp:Panel>
</div>
Code Behind:
protected void GridViewDept_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//some other code
if (delSuccess)
{
donePanelLabel.Text = "Record deleted!";
ModalPopupExtDone.Show();
this.RefreshGridView();
}
else
{
donePanelLabel.Text = "Record not deleted! Please try again!";
ModalPopupExtDone.Show();
}
}
What am I doing wrong?

asp.net c# validation

I am trying to create a simple form that uses radio buttons. I set the radio button to AutoPostBack = True, this way if the radio button is true/false, a subpanel is Shown or Hidden. The radio buttons are required fields. I also have a hidden textbox that the value of the selected radio button is inserted and this textbox is what I validate against (empty or not).
Problem 1:
This works until you go to submit and the validation fails. The validation messages show, then when you click on one of the radio buttons with AutoPostBack = True, all the validation disappear. I can resolve this by adding Page.Validate() to the method that runs when the radio button is clicked. But, I do not want the Page.Validate() to run unless the page was already showing validation errors (so it will not re-validate unless the form was already submitted and failed the validation).
As it stands, before the form is submitted and fails validation: when you click on any radio button question, all the other questions requiring validation show the validation error. I am only looking to overcome the AutoPostBack which is clearing all the validation messages that are shown when you had click submit.
Problem 2:
I would like to be able to change the color of the question if it does not pass validation. I added the javascript to override the default .net settings. I got this to work, but only when you click the submit button and not after a RadioButton AutoPostBack.
Currently, When you click submit all the required questions turn red and also display the required validation message. But if you click a radio button to start fixing the validation errors, on the AutoPostBack, the all the questions that were now red in color changes back to the orignal black and the required validation message is still shown. How can I call the Javascript to run again along with the Page.Validation() in the code behind method?
Any help would be greatly appricated! Thanks
Below is an example of the code so far.
ASPX Code:
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell CssClass="question">
<label>4. Have you had an abnormal result from a prenatal test (e.g. amniocentesis, blood test, ultrasound)?</label>
</asp:TableCell>
<asp:TableCell CssClass="answer">
<ul class="selectGroup">
<li>
<asp:RadioButton ID="Q4_true" runat="server" Checked='<%# Bind("Q4_yes") %>' Text="Yes"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" /></li>
<li>
<asp:RadioButton ID="Q4_false" runat="server" Checked='<%# Bind("Q4_no") %>' Text="No"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" />
</li>
<asp:TextBox ID="Q4_validationBox" runat="server" CssClass="hiddenField" Enabled="false"
Text=''></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableViewState="true" ControlToValidate="Q4_validationBox"
Display="Dynamic" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ul>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Code Behind
protected void RB_QuestionSubPane_YN(object sender, EventArgs e)
{
RadioButton radio_Selected = (RadioButton)sender;
string radio_QuestionID = Convert.ToString(radio_Selected.ID);
(((TextBox)FormView1.FindControl(strQuestionID + "_validationBox")).Text) = radio_Selected.ID.ToString();
Page.Validate();
}
JavaScript
ValidatorUpdateDisplay = function (val) {
var ctl = $('#' + val.controltovalidate);
var eCount = 0;
for (var i = 0; i < Page_Validators.length; i++) {
var v = Page_Validators[i];
if (v.controltovalidate == val.controltovalidate) {
if (!v.isvalid) {
eCount++;
ctl.addClass('validationError');
$('td.question:eq(' + i + ')').addClass('red');
}
};
}
if (eCount > 0) {
ctl.addClass('validationError');
} else {
ctl.removeClass('validationError');
$('td.question:eq(' + i + ')').removeClass('red');
}
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
It sounds like what you really need is custom validation. That way you can fully customize your validation to meet your needs.
Here is a simple example:
<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{
//put your javascript logic here
}
//-->
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="direction" Text="left" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="direction" Text="right" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
Server Side
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//validate is successful.
}
}

Validation Ignored with PostBackUrl or Response.Redirect Using C#

I have a form with some custom validation. There is a button on the form that should take the user to a 'confirm page' to show all the details of an order.
On-Page Validation
<asp:TextBox ID="txtBillingLastName" Name="txtBillingLastName"
runat="server" CssClass="txtbxln required"></asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorBillLN" runat="server"
ControlToValidate="txtBillingLastName"
OnServerValidate="CustomValidatorBillLN_ServerValidate"
ValidateEmptyText="True">
</asp:CustomValidator>
Validator code behind
protected void CustomValidatorBillLN_ServerValidate(object sender, ServerValidateEventArgs args)
{
args.IsValid = isValid(txtBillingLastName);
}
However, if I add PostBackUrl or Response.Redirect to the button onclick method, all the validation controls are ignored.
I could call all the validation methods with the onclick method, but that seems a less than an elegant solution.
I've tried setting CausesValidation=False with no luck.
Any suggestions?
Of course that validation IS ignored if you redirect unconditionally. You should call this.IsValid before you redirect like
protected btRedirect_Click( object sender, EventArgs e )
{
if ( this.IsValid )
Response.Redirect( ... );
}
Check this code
void ValidateBtn_OnClick(object sender, EventArgs e)
{
// Display whether the page passed validation.
if (Page.IsValid)
{
Message.Text = "Page is valid.";
}
else
{
Message.Text = "Page is not valid!";
}
}
void ServerValidation(object source, ServerValidateEventArgs args)
{
try
{
// Test whether the value entered into the text box is even.
int i = int.Parse(args.Value);
args.IsValid = ((i%2) == 0);
}
catch(Exception ex)
{
args.IsValid = false;
}
}
And Html side code
<form id="Form1" runat="server">
<h3>CustomValidator ServerValidate Example</h3>
<asp:Label id="Message"
Text="Enter an even number:"
Font-Name="Verdana"
Font-Size="10pt"
runat="server"/>
<p>
<asp:TextBox id="Text1"
runat="server" />
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<p>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
For further information check Custom validator
Hope my answer help you to solve your problem.

Categories

Resources