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.
Related
I'm Working in this program for two days and i can not find out where I'm doing Wrong.If you could help me I really appreciate it .The Problem is when I enter 11111 for my the curator ID and leave the name Box Empty,it is not suppose to saved the curator ID .After if I put something in the box and i enter 11111 for the Curator ID it says "ID already exist please try again".
private void SaveCuratorBtn_Click(object sender, RoutedEventArgs e)
{
curator Curator = new curator();
try
{
Curator.ID = CuratorIDbox.Text;
bool sameid = false;
for (int i = 0; i < curatorlist.Count; i++)
{
if (curatorlist[i].ID == Curator.ID)
{
sameid = true;
break;
}
}
if (sameid)
MessageBox.Show("ID already exist please try again !");
else
{
curatorlist.add(Curator);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
try
{
bool checkingname = false;
Curator.NAME = CuratorNamebox.Text;
checkingname = true;
if (checkingname)
{
MessageBox.Show("Curator Saved");
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
if (sameid)
{
MessageBox.Show("ID already exist please try again !");
}
else
{
curatorlist.add(Curator);
}
This code block is doing the following:
If the ID already exists, show an error (good!)
If the ID doesn't exist, add the whole Curator to curatorlist.
What you need is another step of validation in your code to make sure that box the name textbox and the ID textbox contain information. You could achieve this like so (replace the names of course):
else
{
if(string.IsNullOrEmpty(NameTextbox.Text) || string.IsNullOrEmpty(IdTextbox.Text)
{
MessageBox.Show("Uh oh!")
} else {
curatorlist.add(Curator);
}
Here you're checking if the textboxes are empty before even thinking about adding the Curator to curatorlist. If you need to make other checks (such as no numbers [1,2,3,4] in your NameTextbox), there are multiple ways of doing so.
You say that "when I enter 11111 for my the curator ID and leave the name Box Empty,it is not suppose to saved the curator ID"; but there is nothing in the sample code that you have provided which prevents this. That might be what you want; but you haven't coded it that way: the "curatorlist.add(Curator);" will add the curator to the collection regardless of what is in the Name box.
P.S. consider using a Dictionary, as the lookup will be faster.
I have an application that performs a time consuming task when the user selects an item for a listbox.
When a user selects a show the application will retrieve all the shows information form the tvdb and the display it in the Ui.
The problem occurs when a user quickly changes selection while the show is still loading.
I would like to make it so that a user could change their mind and then make another selection while the first was loading and have that information displayed in the Ui.
I have created a simple demonstration application to show the problem : Demo App .
This is what i tried to do
List box selection event handler
private void lb1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string sid = lb1.SelectedItem.ToString();
try
{
LoadSeries(Int32.Parse(sid));
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid series id");
}
}
LoadSeries
private void LoadSeries(int _seriesId)
{
Task<TvdbSeries> series = Task.Factory.StartNew(() =>
{
TvdbSeries seriesloaded = null;
try
{
seriesloaded = m_tvdbHandler.GetSeries(_seriesId, TvdbLanguage.DefaultLanguage, true, true, true, true);
}
catch (TvdbInvalidApiKeyException ex)
{
MessageBox.Show(ex.Message);
}
catch (TvdbNotAvailableException ex)
{
MessageBox.Show(ex.Message);
}
return seriesloaded;
}
);
series.ContinueWith((antecedent) =>
{
UpdateSeries(series.Result);
},
TaskScheduler.FromCurrentSynchronizationContext()
);
}
If a user changes selection quickly the application errors on the line seriesloaded = m_tvdbHandler.GetSeries(_seriesId, TvdbLanguage.DefaultLanguage, true, true, true, true); and shows this message in the debugger "WebClient does not support concurrent I/O operations."
I did find out that it is because I am making a new request before the last one is finished but I have no way of chaining the code in m_tvdbHandler.GetSeries because its functionality comes from library i am using and some one else wrote .
This is the library tvdblib , I am sure the problem is with how I am doing things and not the library .
when a user makes a selection you can disable the UI till the information is loaded completely and display a message at the bottom loading please wait. Once everything is loaded, enable the Ui and hide the message.
You are posting this question as a C#5.0 question, so you should be using async/await as much as you can.
private Task<TvdbSeries> LoadSeriesAsync(int _seriesId)
{
return Task.Run(() =>
{
TvdbSeries seriesloaded = null;
try
{
seriesloaded = m_tvdbHandler.GetSeries(_seriesId, TvdbLanguage.DefaultLanguage, true, true, true, true);
}
catch (TvdbInvalidApiKeyException ex)
{
MessageBox.Show(ex.Message);
}
catch (TvdbNotAvailableException ex)
{
MessageBox.Show(ex.Message);
}
return seriesloaded;
}
);
}
It would be much better if there was a LoadSeriesAsync.
One way to do it would be to disable lb1 while retrieving the series.
private async void lb1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string sid = lb1.SelectedItem.ToString();
try
{
lb1.IsEnabled = false;
var series = await LoadSeriesAsync(Int32.Parse(sid));
UpdateSeries(series);
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid series id");
lb1.IsEnabled = true;
}
}
I am having a problem and had been searching the web and couldn't find anything that will help me.
this is my problem.
Im working in WinForm , c#
I have a grid where is a Column of type GridViewDateTimeColumn.
When the user update a row I check it in the event RowValidating and if I get a repeated date or other error I show the user a message and I do e.cancel = true to not validate the row.
But then If I press ESC. I cannot cancel all the changes like it usually does before
Any idea how to do it?
Here is my code:
private void grdPirteyMenahel_RowValidating(object sender, RowValidatingEventArgs e)
{
try
{
Cursor.Current = Cursors.WaitCursor;
if (e.Row != null)
{
//Generate a service to connect to DB
var factory = new MezumanimChannelFactory<IKerenService>(ServiceConsts.SERVICE_KEREN);
var service = factory.CreateChannel();
string sError = string.Empty;
//here I call a SP in the database that check if the dates are correct (column of dates are call it "MiTaarich" and "AdTaarich".
//The SP return a String with the error, if there is no error it will return and empty string
sError = GetErrorPirteySacharMenahel(Convert.ToDateTime(e.Row.Cells["MiTaarich"].Value), Convert.ToDateTime(e.Row.Cells["AdTaarich"].Value), Convert.ToInt32(e.Row.Cells["Kod"].Value));
if (sError != string.Empty)
{
e.Cancel = true;
RadMessageBoxHelper.Alert(sError);
}
}
}
catch (Exception ex)
{
Elad.Mezumanim.Client.Utils.Log.LogUtil.write(ex);
e.Cancel = true;
RadMessageBoxHelper.Alert(Messages.DataDisplayError, this);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
I also tried adding this code when i get the error:
DataTable dt = (grdPirteyMenahel.DataSource as DataTable);
dt.RejectChanges();
But this recover the value of date as it was before (what is good) but doesn't let me get out of the row when I press ESC
Any idea how to solve it?
thank you very much
best regards
Iair
Ok, I asked Telerik about it, and theY gave me a solution.
its not a real solution its more like a patch a workaround but for the moment its good for me.
http://www.telerik.com/community/forums/winforms/gridview/esc-in-gridviewdatetimecolumn-inside-raddatagridview-after-i-did-an-e-cancel-true-in-row-validation.aspx
thanks
Iair
I have a code block that leads to a "Internet Explorer cannot display the webpage" error. When I click the submit button, with NONE of the radio buttons checked, the web page status bar displays "waiting for response from host" and then display the "Internet Explorer cannot display the webpage". When I walk through the code in visual studio, the code executes fine, and none of the catch blocks are executed.
How can I trap the error and determine why the error page is being displayed?
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (rbtnSearchBy1.Checked)
{
Server.Transfer("ViewEmpHistory.aspx");
}
if (rbtnSearchBy2.Checked)
{
Server.Transfer("SearchEmp.aspx");
}
if (rbtnSearchBy3.Checked)
{
Server.Transfer("ViewEmpCard.aspx");
}
}
catch (ThreadAbortException)
{
throw;
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Whatever .cs page your "btnSubmit_Click" is on, put a breakpoint on that page_load event.
Also, put a breakpoint on the page_load event of "ViewEmpHistory.aspx", "SearchEmp.aspx" & "ViewEmpCard.aspx". (so now you have four breakpoints).
Step through the project again and make sure all parameter values are being passed correctly, also make sure that you have correct logic (if applicable) for If (!PostbacK) conditions etc.
HTH
if you don't select one radiobutton it's normal that you don't enter in your catch , because your application no throw exception.
but you can view your eventlog
Enter in your cmd : eventvwr to access your event log
To debug these kind of issues, I often find it easier to use Tracing.
You can turn on tracing at the application level, or at the page level.
Your method call will then become:
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (rbtnSearchBy1.Checked)
{
Server.Transfer("ViewEmpHistory.aspx");
}
if (rbtnSearchBy2.Checked)
{
Server.Transfer("SearchEmp.aspx");
}
if (rbtnSearchBy3.Checked)
{
Server.Transfer("ViewEmpCard.aspx");
}
}
catch(Exception ex)
{
Trace.Warn("Exception Caught", "Exception: btnSubmit_Click", ex);
}
}
You can look at the trace log by then navigating to the Trace Viewer.
What you've done is not exactly well structured. It's cleaner if the blocks are exclusive - which is why I've added the else statements to the code below. I've also indicated where you would want to handle the state where no button is checked in comments.
But you're right, there isn't any exception being thrown. Your code didn't throw one, and when you end processing a request without returning any type of response it doesn't cause an exception.
if (rbtnSearchBy1.Checked)
{
Server.Transfer("ViewEmpHistory.aspx");
}
else if (rbtnSearchBy2.Checked)
{
Server.Transfer("SearchEmp.aspx");
}
else if (rbtnSearchBy3.Checked)
{
Server.Transfer("ViewEmpCard.aspx");
}
else
{
// Here's where the logic will flow to if no radio button is clicked.
// We could
// * Server.Transfer to a default location
// * Throw an exception
// * Do nothing, which returns no response, and causes
// IE to complain that it could not display the webpage.
}
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);