i have a confirm and alert message box.
both are getting displayed at the right time.
but in confirm box when i press cancel the applyaction_button_click is getting executed, which should not happen as i return false.
Similar is the case with alert box which returns false still applyaction_button_click is getting executed.
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
ApplyAction_Button.Attributes.Add("onclick", "ShowConfirm();");
}
protected void ApplyAction_Button_Click(object sender, EventArgs e)
{
// Action to be applied
}
JS function:
function ShowConfirm() {
//check if checkbox is checked if is checked then display confirm message else display alert message
var frm = document.forms['aspnetForm'];
var flag = false;
for (var i = 0; i < document.forms[0].length; i++) {
if (document.forms[0].elements[i].id.indexOf('Select_CheckBox') != -1) {
if (document.forms[0].elements[i].checked) {
flag = true
}
}
}
if (flag == true) {
if (confirm("Are you sure you want to proceed?") == true) {
return true;
}
else {
return false;
}
} else {
alert('Please select at least Checkbox.')
return false;
}
}
thanks
When you have a client side event on an asp server control that has a server event and both get triggered with the same action, returning true or false on the client doesn't stop it from executing its server event.
You could try to prevent the button's server event from executing by doing some kind of postback in your javascript code.
Related
I have a button in my page which is used to save data of gridview which is dynamically populated. Before saving I want to check some condition. The javascript function is as follows:
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("This will completely delete the project. Are you sure?")) {
confirm_value.value = "Yes";
}
else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" onClientClick="Confirm()"></button>
The code behind is as follows:
protected void lnkBtn_Click(object sender, EventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
{
MyAlert("No clicked");
}
}
else
{
MyAlert("No Text found.");
}
}
Now the problem is since I have the function Confirm() in the onClientClick event, the confirm dialog appears the moment the user clicks the button, instead it should appear only when a string is found in txtID.
I tried to modify the code by removing the onClientClick event as follows:
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" ></button>
protected void lnkBtn_Click(object sender, EventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "confirm", "Confirm();", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
if (confirmValue == "No")
{
MyAlert("No clicked");
}
}
}
Here also it is not working properly. The confirmValue is getting the value but using it only during the subsequent click of the button. It is not passing value stored during the present click event instead the previously stored value is passed to if block. Please help to find what should I do get it right.
Thanks.
I need enter manually some values during a loop for. I'm using C# ASP.Net with WebForms.
I'm trying this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace systemII
{
public partial class MY_System : System.Web.UI.Page
{
private List<String> List = new List<string>();
private bool loop = false;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
while (loop) { }
for (int i = 1; i <= 10; i++)
{
string a = "A" + i.ToString();
if (i == 4 || i == 5)
{
loop = true;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
else
{
List.Add(a);
}
}
}
protected void Button2_Click(object sender, EventArgs e) // modal button
{
string b = "BB";
Lista.Add(b);
loop = false;
return;
}
}
}
But the Modal appear on screen after end of loop. I need pause the loop until I enter the textbox value.
Any can help me? Sorry for my bad english.
In ASP.Net you cannot just pause the server-side code since the server-side code is always executed fully (never partially) even if you use asynchronous page in ASP.Net and also, server-side is never connected to browser but is executed in a separate process. Browser never knows and doesn't care what's happening on server-side, and the server-side doesn't know nor cares about what browser is doing, so it's impossible to connect server-side code to browser the way you want.
However, you can simulate what you want by breaking from the loop when the first index =4 is reached and modal popup script emitted. Then you can do a similar thing for i= 5 when user has inputted values for i=4 and page has posted back. But, the values of i that were successfully handled for input will need to be tracked across requests from browser, which is done in code below by setting a ViewState variable called HandledValues which is just a collection of List of string type.
So the workflow if you use this code will be: User will be prompted to input values for i=4 in a modal popup and then when a button Button1 is clicked and page posts back, the user will be prompted to input values for i = 5 in a modal popup.
protected void Button1_Click(object sender, EventArgs e)
{
//a list of values handled is stored in ViewState as ValuesHandled
List<string> handledValues = new List<string>();
if (ViewState["ValuesHandled"] != null) {
List<string> handledValues = (ViewState["ValuesHandled"] as List<string>;
}
for (int i = 1; i <= 10; i++)
{
string a = "A" + i.ToString();
//check if i = 4 has had its values input successfully
if (i == 4 && !handledValues.Contains(i.ToString()))
{
loop = true;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
handledValues.Add(i.toString());
//break the loop since we need to return to browser for input by user
break;
}
else if (i == 4 && handledValues.Contains(i.ToString()))
{
//remove handled value if no modal popup needed to be opened
handledValues.Remove(i.ToString())
}
else if (i == 5 && !handledValues.Contains(i.ToString()))
{//check if i = 5 has had its values input successfully
loop = true;
handledValues.Add(i.toString());
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
//break the loop since we need to return to browser for input by user
break;
}
else if (i == 5 && handledValues.Contains(i.ToString()))
{
//remove handled value if no modal popup needed to be opened
handledValues.Remove(i.ToString())
}
else
{
List.Add(a);
}
}
//update the ViewState for ValuesHandled
ViewState["ValuesHandled"] = handledValues;
}
I am trying to validate windows form with try catch and so far I succeeded. My goal is when someone forgot to fill the gap or put in incorrect entry, catch returns messagebox with a warning. Now I also have Validating event on every control I want to validate so when somebody leave it empty or in incorrect format it will show the error next to the control. That seems ok so far (for me, at least) but my issue is, that if user doesn't even click to one box it only shows message box, but it won't highlight wrong controls.
Below is my code:
private void createButton_Click(object sender, EventArgs e)
{
try
{
Book newBook = new Book(titleBox.Text, authBox.Text, Convert.ToInt32(yearBox.Text), Convert.ToInt32(editBox.Text), pubComboBox.Text, descBox.Text);
bookList.Add(newBook);
booklistListBox.DataSource = bookList;
}
catch (FormatException)
{
MessageBox.Show("You probably missed a gap or put in incorrect form");
}
}
and those validating events:
private void titleBox_Validating(object sender, CancelEventArgs e)
{
if (titleBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(titleBox, "Title is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(titleBox, "");
}
}
private void authBox_Validating(object sender, CancelEventArgs e)
{
if (authBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(authBox, "Author is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(authBox, "");
}
}
private void yearBox_Validating(object sender, CancelEventArgs e)
{
if (yearBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(yearBox, "Year is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(yearBox, "");
}
}
private void editBox_Validating(object sender, CancelEventArgs e)
{
if (editBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(editBox, "Edition is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(editBox, "");
}
}
private void pubComboBox_Validating(object sender, CancelEventArgs e)
{
if (pubComboBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(pubComboBox, "Publisher is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(pubComboBox, "");
}
}
private void descBox_Validating(object sender, CancelEventArgs e)
{
if (descBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(descBox, "Description is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(descBox, "");
}
}
So is there way to, I don't know, change focus or something like that, forced with pressing the create button?
Thank You
Try using ValidateChildren():
private void createButton_Click(object sender, EventArgs e)
{
bool gotIssues = this.ValidateChildren();
if (gotIssues)
{
// someone didn't validate well...
}
}
So, the issue here is that you want to have it highlight in either of two scenarios:
1) When you leave the field and its contents are invalid (empty in this case)
2) When you click the create button and the field in question has invalid contents
And so I would create a single textBox_checkIfEmpty(object sender, EventArgs e) method:
private void textBox_checkIfEmpty(object sender, EventArgs e)
{
var asTb = sender as TextBox;
if (asTb != null && asTb.Text.Trim() == String.Empty)
{
errorProvider.SetError(asTb, "I'll leave it to you to abstract the error message appropriately");
e.Cancel = true;
}
else
{
errorProvider.SetError(asTb, "");
}
}
Then, you can set this method as the handler for your Validate event on your desired required controls, and you can also call the same method from the create button's handler, looping through the required TextBox instances and executing the method on each.
UPDATE
J. Hudler's ValidateChildren solution would be a more (developer) efficient tail to mine, as opposed to looping through the desired controls. That said, if the form has many children, and you only need to validate several, it might be helpful to loop still. Just depends on your specific scenario. My only other question is whether or not ValidateChildren is infinitely recursive, or if it only goes one level down (immediate children rather than all descendants).
the event validating for control call when the mouse click on the control and then leave it from the control. In your case when the user does not click on the control it will not trigger the validating event. U can do this by making your own function and call them on creat event.
private void button1_Click(object sender, EventArgs e)
{
textBox1_Validating(sender);
}
public void textBox1_Validating(object sender)
{
MessageBox.Show("validating");
errorProvider1.SetError(textBox1, "provide");
}
I want to generate an alert box on button click. I have written like this
protected void btn_submit_click(object sender, ImageClickEventArgs e)
{
btn_submit.OnClientClick = #"return confirm('Student has not completed all the steps? Are you sure you want to submit the details?');";
bool type = false;
if(type==true)
{
//If clicks OK button
}
else
{//If clicks CANCEL button
}
}
Alert box comes correctly. But how could I get the values from code behind?please help.
When confirm returns false, then there is no postback since the click event in the javascript is cancelled. If you want to have the postback after clicking cancel you need to change your code a little:
serverside:
protected void Page_Load(object sender, System.EventArgs e)
{
btn_submit.Click += btn_submit_click;
btn_submit.OnClientClick = #"return getConfirmationValue();";
}
protected void btn_submit_click(object sender, ImageClickEventArgs e)
{
bool type = false;
if(hfWasConfirmed.Value == "true")
{
//If clicks OK button
}
else
{//If clicks CANCEL button
}
}
on the client:
<asp:HiddenField runat="server" id="hfWasConfirmed" />
<asp:Panel runat="server">
<script>
function getConfirmationValue(){
if( confirm('Student has not completed all the steps? Are you sure you want to submit the details?')){
$('#<%=hfWasConfirmed.ClientID%>').val('true')
}
else{
$('#<%=hfWasConfirmed.ClientID%>').val('false')
}
return true;
}
</script>
</asp:Panel>
u can try this also
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (grdBudgetMgr.Rows.Count > 0)
{
if (confirmValue == "Yes")
{
}
}
}
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Are you sure Want to submit all Budgeted Requirement ?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
I have the following code to check that a query string has not changed:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Label_Error.Visible = false;
string query_string = Request.QueryString["GUID"].ToString();
Session["GUID"] = query_string;
}
else
{
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
}
}
Now, I have this code in a button-click event handler to check that the value of the query string has not changed (again):
protected void ImageButton_LogIn_Click(object sender, ImageClickEventArgs e)
{
Validation val = new Validation();
string GUID = "";
string query_string = "";
try
{
GUID = Session["GUID"].ToString();
query_string = Request.QueryString["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (val.EmptyString(GUID) == true || val.checkTransactionGUIDExists(GUID) == false || GUID.Equals(query_string) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
Now, the problems are two:
1) if I change the query string in the URL and click on the button, the user is not redirected to the error page.
2) if I change the query string in the URL and hit enter in the address bar, the user is not redirected to the error page.
What I want basically is that, when the user is redirected to the web page, it saves the query string into a session. If the user changes the value of the query string in the address bar, and either pressed enter in the address bar or presses my button, he is redirected to the error page.
However, my code is failing. Can anyone help please? Thanks :)
How about this instead?
protected void Page_Load(object sender, EventArgs e)
{
// Always get the query string no matter how the user go to this page
string query_string = Request.QueryString["GUID"].ToString();
// Only store the query string in Session if there is nothing in Session for it
if(null == Session["GUID"])
{
Session["GUID"] = query_string;
}
if (!this.IsPostBack)
{
Label_Error.Visible = false;
}
// Always check to see if the query string value matches what is in Session
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
This should solve your problem of the Session value being overwritten when a query string is put into the address bar and enter is pressed by the user.
I think you problem is that Response.Redirect needs the false at the final of the sentence like Response.Redirect("CheckOutErrorPage.htm", false); becouse that you have it inside the try cath the error will be throw.
I hope that help you.