I created a simple e_form with insertion button, I wanna add pop up message if the insertion process succeed, I add it alone and it works but when combining it with my code I got an error.
my code is
protected void ImageButton1_Click(object sender, EventArgs e)
{
// connection stuff...
cmd.Parameters.AddWithValue("#full_name", TextBox1.Text);
cmd.Parameters.AddWithValue("#dob", TextBox5.Text);
cmd.Parameters.AddWithValue("#id_no", TextBox2.Text);
int result;
result=cmd.ExecuteNonQuery();
if result >0
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"script", "<script>data has been added successfully</script>");
con.close();
}
}
I think you need to check few things before executing the SQL query.
i)are your html DOM elements are populated as soon as the page because RegisterStartupScript method places javascript at the bottom of the page just before closing of the element.
ii)is our ExecuteNonQuery returning result.
RegisterStartupScript (type type,string key,string script,bool addtags) is mostly used for scripts that must run on page load but your code must run on image button click,so use below method
int result = 1;
if (result==1)
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"script", "alert('data has been added successfully');", true);
}
This should work..Cheers
The if requires brackets
if(result > 0)
I would also suggest adding a label or alert. The ,true adds the tags
Page.ClientScript.RegisterStartupScript(this.GetType(),
"script", "alert('data has been added successfully');", true);
Related
I have two near identical forms on the site and only one of them works. On firing button click they're supposed to collect text from checkbox fields and email that information on. One of the forms try is completely ignored and the error message in catch is displayed
Using the working form on the new page still won't work makes me think there may be issues with the page, but deleting the aspx and aspx.cs pages and rewriting them when it may not be that serious is not something I want to do if it's not necessary. I've tried removing 'if (IsPostBack)' and 'if (LiabilityCheckBox.Checked == true)' on the form with issues among other things, but nothing seems to help.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
if (LiabilityCheckBox.Checked == true)
{
// validate the Captcha to check we're not dealing with a bot
bool isHuman = ExampleCaptcha.Validate(CaptchaCodeTextBox.Text);
CaptchaCodeTextBox.Text = null; // clear previous user input
if (!isHuman)
{
lblCaptchaError.Visible = true;
lblCaptchaError.Text = "Incorrect Code. Please try again!";
}
else
{
try
{
//some code
lblRegMessage.Text =
("Registration Successful. Thank you for entering."
+ "Please click button below to finalise Payment and Registration.");
// Clear the textbox values
//Show Continue Button.
ContinueButton.Visible = true;
}
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
}
}
else
{
lblMessage.Text = ("You must check the Liability check box to continue");
}
}
}
I am expecting the result of filling out the form to be the mail is sent and a message appears telling the user "Registration Successful. Thank you for entering."
What I am getting is this:
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
As I checked, your code missing some closing brackets. Please check the brackets are properly closed and in the series.
I have a problem doing it for a week I'm working on and I would love to find a solution ... it is a web application in asp.net and c #
I have a related listeview a database which I am inserting the students .. and I'd like not exceed 30 insertions ... the goal is that if I try to enter the 31th student I must be stopped displaying a warning message
I try Sev code which seems to me that here is the nearest that I put in my page load, but unfortunately its not working
if (ListView1.Items.Count>30)
{
ClientScript.RegisterStartupScript(this.GetType(),
"myalert",
"alert('" + "Dsl .. étudiant !!" + "');", true);
}
Note: All you have said in your problem description is "...but unfortunately its not working", so I don't know for sure what the problem is. I'm assuming that you never actually make it inside the if-block.
You mention that the code in your question is in Page_Load. Just to be safe, I would put it in the databound event of your ListView:
ListView1_DataBound(Object sender, EventArgs e)
{
if (ListView1.Items.Count>30)
{
ClientScript.RegisterStartupScript(this.GetType(),
"myalert",
"alert('" + "Dsl .. étudiant !!" + "');", true);
}
}
This way you know that your ListView1.Items.Count is correct and up-to-date.
i m opening an Webpage(Clock.aspx) from window.showModalDialog of javascript.In the Clock.aspx i have a button and i want that when the user click on that button the Clock.aspx page will be closed. I dont want to use onClientClick() method of javascript as some server side database insertion is going on and after the insertion i want to close this page.
The Code behind of the button is as follows:-
protected void btnStop_Click(object sender, EventArgs e)
{
_nonProduction = new NonProduction();
if (Session["LastNonProdTimeID"] == null)
{
}
else
{
int NonProdTimeEntryID = Convert.ToInt32(Session["LastNonProdTimeID"]);
//Updating the TimeSpent
isTimeSpentUpdated = _nonProduction.UpdateTimeSpentInDB(NonProdTimeEntryID);
if (isTimeSpentUpdated == true)
{
string timespent = Convert.ToString(_nonProduction.GetTimeSpent(NonProdTimeEntryID));
string msg = "Total time consumed in " +HiddenTaskname.Value.ToString()+": " + timespent.ToString() + " Minutes";
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
//ShowPopUpMsg(msg);
}
else
{
}
}
}
Here when i m clicking on the Button one more (Clock.aspx)pop up is appearing and window is not closing. Please help me that how i close the ShowModalDialog from server side code. I m using Script manager in my page also.
Thanks in Advance.
I had added <base target="_self">to the head section of the clock.aspx page and then it works fine for me.
For mine, I have a function in normal javascript that closes the page in the aspx.
In the code behind, if the update is successful, it calls that function.
// this function is to be called by the popup windows to refresh the opener using specific office code, and close self
function allDoneOffice(office)
{
var opener = self.opener;
if (opener.doRefresh) opener.doRefreshWithOfficeCode(office);
window.open('','_self',''); // IE warning hack
self.close();
}
// update the record
bool b = report.SaveModifiedToDB();
if (b)
{
// don't close the page if nothing was updated
ClientScript.RegisterStartupScript(this.GetType(), "load", "<script type=\"text/javascript\">\n" +
"allDoneOffice('" + report.OfficeCode + "');" + "<" + "/script>");
}
else
{
lblResults.Text += " Unable to save modified report to the database.";
}
Use this code below should work in IE
Response.Write("<script language='javascript'> { self.close() }</script>");
I have a problem with this that works for one button and not for another.
The one that works is a button that calls a ModalPopup to add a new row to a GridView inside an UpdatePanel. If it's successful, it pops up an alert with a message, else another alert with the Exception message. The code is very similar to the other one's, except it's in a ModalPopupExtender.
The button that throws the known exception about the EventValidation goes as follow:
Web:
<asp:Button ID="btnAlquilar" runat="server" Text="Alquilar" CssClass="AdminButtons"
OnClientClick="Click_Alquilar(); return false"/>
The JavaScript function it calls
function Click_Alquilar() {
if (index == '') {
alert("Debe elegir una película para alquilar");
}
else {
if (confirm("¿Quiere alquilar la película '" + selected.childNodes[2].innerText + "'?")) {
__doPostBack('<%= btnAlquilar.UniqueID %>', index);
}
}
}
Where index is the index of the selected row in the GridView (done with a similar architecture, and works fine).
The code-behind starts in the Page_Load method, and calls the function I'm having trouble with:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{...}
else
{
ProcessAjaxPostBack(sender, e);
}
}
private void ProcessAjaxPostBack(object sender, EventArgs e)
{
if ((Request.Params["__EVENTTARGET"] != null) && (Request.Params["__EVENTARGUMENT"] != null))
{
...
if (Request.Params["__EVENTTARGET"] == this.btnAlquilar.UniqueID)
{
index = Convert.ToInt32(Request.Params.Get("__EVENTARGUMENT").TrimStart('r', 'o', 'w'));
btnAlquilar_Click(Request.Params.Get("__EVENTARGUMENT"));
}
}
}
protected void btnAlquilar_Click(string id)
{
string message = "";
if (BAC.BAC.CheckUserAge(lblUserId.Text) < Convert.ToInt32(dgvPeliculas.Rows[index].Cells[7].Text))
{
btnBorrar.Visible = false;
btnEditar.Visible = false;
btnNuevo.Visible = false;
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No tiene la edad mínima para alquilar la película.')", true);
}
else
{
try
{
BAC.BAC.NewAlquiler(lblUserId.Text, dgvPeliculas.Rows[index].Cells[0].Text, dgvPeliculas.Rows[index].Cells[9].Text);
}
catch (Exception ex)
{
message = Change_ExceptionMessage(ex.Message);
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No se pudo alquilar la película: " + message + "')", true);
}
}
}
The RegisterClientScriptBlock method is THE SAME I use for the other button (which doesn't do anything more complex than this one: if things are wrong, it changes the text of a label in the Popup and shows the alert; if it's right, it loads the GridView and shows the success alert), and works there. Here, it throws the exception "EnableEventValidation is true so...". I have this button registered for Event Validation on Render:
protected override void Render(HtmlTextWriter writer)
{
this.Page.ClientScript.RegisterForEventValidation(btnAlquilar.UniqueID);
base.Render(writer);
}
So why does this happen here? Why it doesn't work this time?
EDIT: Now that I check, the label changed by the working button in the ModalPopup is wrapped in an UpdatePanel. I don't know if it matters, but just to note it.
EDIT2: The page also works within a Master page. Don't know if it's of any use. I have tried wrapping both the Edit button and the GridView with UpdatePanels and using AsyncPostBackTrigger, but still I get the same exception.
OnClientClick="Click_Alquilar(); return false"
instead of this use
OnClientClick="return Click_Alquilar();
and in javascript
use return false;
in functions like
function Click_Alquilar() {
if (index == '') {
alert("Debe elegir una película para alquilar");
return false;
}
else {
if (confirm("¿Quiere alquilar la película '" + selected.childNodes[2].innerText + "'?")) {
__doPostBack('<%= btnAlquilar.UniqueID %>', index);
}
}
}
OK, for those who are interested in it, the problem was with the _doPostBack calls. Since the arguments I passed (_EVENTARGUMENT) were dynamic, I could never register those events through the RegisterForEventValidation method, becuase it asks for two constant strings (AFAIK): the control's UniqueID and the argument it will be passed with it.
So, I stopped passing arguments to the doPostBack other than the button's UniqueID, and passed the variables I was interested in through other media (cheifly, hidden fields values to global variables inside the Page class).
That solved the problem and made the program work as intended. I wrapped the buttons inside the same update panel than the GridView so as to not generate an AutoPostBack and change the Grid's values without having to refresh.
If anybody is interested in the code, I can provide.
I have my own exception based on some condition and want to raise an alert when control comes in this catch block
catch (ApplicationException ex)
{
//want to call window.alert function here
}
Do you mean, a message box?
MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx
It's a bit hard to give a definitive answer without a bit more information, but one usual way is to register a startup script:
try
{
...
}
catch(ApplicationException ex){
Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
}
if you are using ajax in your page that require script manager Page.ClientScript
will not work,
Try this and it would do the work:
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"alertMessage", #"alert('your Message ')", true);
You can use the following extension method from any web page or nested user control:
static class Extensions
{
public static void ShowAlert(this Control control, string message)
{
if (!control.Page.ClientScript.IsClientScriptBlockRegistered("PopupScript"))
{
var script = String.Format("<script type='text/javascript' language='javascript'>alert('{0}')</script>", message);
control.Page.ClientScript.RegisterClientScriptBlock(control.Page.GetType(), "PopupScript", script);
}
}
}
like this:
class YourPage : Page
{
private void YourMethod()
{
try
{
// do stuff
}
catch(Exception ex)
{
this.ShowAlert(ex.Message);
}
}
}
You can also do this :
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showError",
"alert('" + ex.Message + "');", true);
}
this will show the exeption message in the alert box
MessageBox like others said, or RegisterClientScriptBlock if you want something more arbitrary, but your use case is extremely dubious. Merely displaying exceptions is not something you want to do in production code - you don't want to expose that detail publicly and you do want to record it with proper logging privately.
I'm not sure if I understand but I'm guessing that you're trying to show a MessageBox from ASP.Net?
If so, this code project article might be helpful: Simple MessageBox functionality in ASP.NET
Simple use this to show the alert message box in code behind.
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Record Saved Sucessfully');", true);
You can try this:
Hope it works for you..
`private void validateUserEntry()
{
// Checks the value of the text.
if(serverName.Text.Length == 0)
{
// Initializes the variables to pass to the MessageBox.Show method.
string message = "You did not enter a server name. Cancel this operation?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}`
You should try this.
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Sakla Test');", true);