I have an if statement that checks if a textbox is not empty. HOwever, if it True, meaning empty i want it to cancel the rest of the process and go back to my form. Below is the IF statement that i have, i cant figure out how to Cancel the remainder of the process.
if (textBox2.Text.Equals(""))
{
MessageBox.Show("Field is Empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
Calling a method like
DoSomething();
causes it to start executing whatever is inside. In some point, if you no longer wish to continue in execution of that method call, use return statement with no return value for methods returning void or return something for methods with non-void return type, where something is type of the return type.
public void DoSomething()
{
... do something
if (condition)
return; // returns from a method call
}
http://msdn.microsoft.com/fr-fr/library/1dac1663%28v=vs.80%29.aspx
private void validateUserEntry2()
{
// 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 = "No Server Name Specified";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(this, message, caption, buttons,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
if(result == DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}
Related
I have scripts that run on request and are compiled using CodeDomProvider. Here's an example of one:
var yes = SendYesNo();
if (yes)
// Do something
else
// Do something else
Now. SendYesNo displays a box with input from the user. I want to halt the script on that line, until a response is set. And then, take the response and apply it to the variable and continue the execution. So far I've used await/async, but I dislike this idea. Is it possible with something else?
You could use a modal window that returns your parameter. You could either use a standard MessageBox or a customized Form if the input required is more complex.
Something like:
public class SomeForm : Form
{
public bool yesNo
{
get
{
return yesNo;
}
set
{
//set value according to your logic
}
}
}
and in your main Form call it like:
using (var form = new SomeForm())
{
if (form.ShowDialog() == DialogResult.OK)
{
var yesNo = form.yesNo;
if (yes)
// Do something
else
// Do something else
}
}
in case it's just a Yes / No MessageBox you can refer to:
How do I create a message box with "Yes", "No" choices and a DialogResult?
I have a form that the user inputs values that i save in an array but when the user wants to cancel i want the user to be asked a final time if the user wants to go ahead and cancel a reservation. If the user declines this final time i want the program to go back to the GUI and focus on the textbox with all the rows of reservations and not do the cancelation but i show u the code i have written and it asks the user if they are sure and if not it still deletes the reservation and then focus on the textbox. What is wrong in my code?
public void Cancelreservation()
{
int index = lstReservations.SelectedIndex;
bool checkedindex = m_seatMngr.CheckIndex(index);
if (checkedindex)
{
if (!m_seatMngr.CancelSeat(index))
{
if (lstReservations.SelectedIndex == -1)
{
MessageBox.Show("You need to select a row.", "Error!",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
lstReservations.Focus();
}
else
{
MessageBox.Show("The seat is not reserved! No need to cancel
reservation.", "Important Query",
MessageBoxButtons.OK);
lstReservations.Focus();
}
}
else
{
if (MessageBox.Show("Continue to cancel the reservation?",
"Important Query", MessageBoxButtons.YesNo)
== DialogResult.No)
{
lstReservations.Focus();
}
else
{
m_seatMngr.CancelSeat(index);
}
}
}
m_seatMngr
public bool CancelSeat(int index)
{
if (m_vacantList[index] == "Reserved")
{
m_nameList[index] = " - ";
m_priceList[index] = 0;
m_vacantList[index] = "Vacant";
return true;
}
else
{
return false;
}
}
Assuming that m_seatMngr.CancelSeat(index) is the method that actually cancels the seat, you are calling the method twice. The second if statement, half a dozen lines into your code, is this:
if (!m_seatMngr.CancelSeat(index))
... and it seems likely (given the above assumption) that this line will cancel the seat before you even display the MessageBox.
if (!m_seatMngr.CancelSeat(index))
{
// the rest of your code, which displays the messageboxes
}
This is always calling m_seatMngr.CancelSeat, before you've even displayed any messageboxes.
I am currently building my project using windows forms and came across a minor "problem".
I have the user enter an hour which is stored as an int. I want to provide detailed feedback to the user so that they know exactly what they have done wrong should they cause an error.
If no value is given, a format exception is thrown.
If anything but an integer is given, a format exception is thrown.
This means I cannot directly tell the user that the new item could not be added due to EITHER 1) no value or 2) not an integer as they both use the same exception.
How can I solve this and what would be the best solution?
Many thanks.
Use the Int32.TryParse Method and check return value. You can simply check for no value entered before calling TryParse.
Here's an example of usage from MSDN:
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
some example code related to your question; note ValidateData in particular:
// called from ok button click or similar event
private void Accept()
{
if (!ValidateData())
return;
SaveData();
DialogResult = DialogResult.Ok;
Dispose();
}
private bool ValidateData()
{
int val;
if (string.IsNullOrEmpty(mTextBox.Text))
return FailValidation("Value can not be empty.", mTextBox);
if (!int.TryParse(mTextBox.Text, out val))
return FailValidation("Value was not an integer.", mTextBox);
return true;
}
// do something with the value if you need
private void SaveData()
{
}
// post a message to the user, and highlight the problematic control
// always evaluates to false
private bool FailValidation(string pMessage, Control pControl)
{
if (pControl != null)
{
pControl.Focus();
TextBox textBox = pControl as TextBox;
if (textBox != null)
textBox.SelectAll();
}
AlertBox(pMessage);
return false;
}
// quick alert message method
private void AlertBox(string pMessage)
{
return MessageBox.Show
(
pMessage,
Application.ProductName,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1
);
}
Use int.TryParse to check format and than in success case check if integer is in valid range. Use String.IsNulOrEmpty to check for empty string.
If I can suggest a possible alternate solution... The best validation is preventing the bad input in the first place. Can you restrict the values the user can choose by using a control like a time picker or dropdown list? A dropdown list would still be keyboard friendly for powerusers, and it is a little easier for those who prefer a mouse. Wins for everyone.
This is well supported in Winforms. Use the Validating event to check the entry, the ErrorProvider component to report the error. A sample event handler:
private void textBox1_Validating(object sender, CancelEventArgs e) {
int hour;
e.Cancel = true;
if (textBox1.Text.Length == 0) errorProvider1.SetError(textBox1, "Can't be empty");
else if (!int.TryParse(textBox1.Text, out hour)) errorProvider1.SetError(textBox1, "Not a number");
else if (hour < 1) errorProvider1.SetError(textBox1, "Hour too small");
else if (hour > 24) errorProvider1.SetError(textBox1, "Hour too large");
else {
e.Cancel = false;
errorProvider1.SetError(textBox1, "");
}
}
Then you just need to check if all entries were satisfactory. Use the ValidateChildren() method in the dialog's OK button click event handler:
private void OKButton_Click(object sender, EventArgs e) {
if (ValidateChildren()) this.DialogResult = DialogResult.OK;
}
I'm getting a stackverflow error while executing InvokeRequired.
System.StackOverflowException was unhandled
How to fix it?
There is no info i View Details.
FIXED VERSION:
public DialogResult ShowMessage(string msg, string caption, MessageBoxButtons buttons)
{
if (InvokeRequired)
{
Func<DialogResult> m = () => MessageBox.Show(msg, caption, buttons);
return (DialogResult)Invoke(m);
}
else
{
return MessageBox.Show(msg, caption, buttons);
}
}
It's because when InvokeRequired is true, you call the exact same method again and again. You need to use Invoke in order to get the method scheduled to run on the UI thread. In this case, InvokeRequired will be false, and your code will run into the if branch where you actually show the dialog.
Change your code to something along the lines of:
if(InvokeRequired)
{
Func<DialogResult> showMsg = () => ShowMessage(msg, caption, buttons);
return (DialogResult)Invoke(showMsg);
}
You're getting a stackoverflow because the ShowMessage method is stuck in an infinitive loop, because it calls itself over and over when "InvokeRequired"
how can I handle message box reply example if the user click on yes do something if the user click on NO do another thing ?
Example (slightly modified) from the docs:
const string message =
"Are you sure that you would like to close the form?";
const string caption = "Form Closing";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
//Do something for No
}
else if (result == DialogResult.Yes)
{
//Do something else for Yes
}
Addendum: In the event that you're still on .NET 2.0 and don't have access to the var keyword, declare result as a DialogResult. I.e:
DialogResult result = MessageBox.Show(...);
Missed the fact that this was tagged with WPF, so if you're using that then you'd be using the slightly (but not too much) different System.Windows.MessageBox class instead of System.Windows.Forms.Messagebox. The interaction is largely the same, but also uses the MessageBoxResult enum instead of DialogResult, the MessageBoxImage enum instead of MessageBoxIcon, and the MessageBoxButton enum instead of MessageBoxButtons (plural). You should be able to do something like this:
const string message =
"Are you sure that you would like to close the form?";
const string caption = "Form Closing";
MessageBoxResult result = MessageBox.Show(message, caption,
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.No)
{
// Do something for No
}
else if (result == MessageBoxResult.Yes)
{
// Do something else for Yes
}
Since the tag states WPF and NOT WinForms, you will need to do something like this for a MessageBox:
MessageBoxResult result = MessageBox.Show("Foo Bar?", "Confirmation", MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Yes)
{
// yeah yeah yeah stuff
}
else if (result == MessageBoxResult.No)
{
// no no no stuff
}
else
{
// forget about it
}
In addition the dialogs are dealt with differently in WPF as well, note the absence of DialogResult:
SomeDialog dialog = new SomeDialog();
dialog.ShowDialog();
if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
MessageBox.Show("Clicked ok");
else
MessageBox.Show("Clicked cancel");
You should try using google or msdn (the links are clickable).
Anyways, you should check the value of the messageboxresult returned by the show method.
http://msdn.microsoft.com/en-us/library/ms598674.aspx
The best for me is
if (MessageBox.Show("Are you sure you want to close the window ?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No)
{
//do NO stuff
}
else
{
//do YES stuff
}
DialogResult result = MessageBox.Show("Some Text", "Title", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{
// do something
}
Here is an example:
DialogResult userSelection = MessageBox.Show("Some question","Question",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
// Do something with userSelection
childwindow's in WPF are asynchronous actions. You have to handle the Close event, and inside your close event then you can perform your logic.