Close current form if dialog results for dialogbox is cancel - c#

I have a Form (frmcustlist).
At one time on this list i scan the list using a dataset and check if it now 0 (no customers left).
At this stage i have an input box pop up (dialog) to ask a new customer name.
If they press OK everything is fine. I also have validation on the box for the input.
However if they press CANCEL, i can get it to escape out of the dialog, but not close frmcustlist that the dialog was called from.
using (inputbox ipfirst = new inputbox("Enter Customer First Name:", "", ""))
{
if (ipfirst.ShowDialog() == DialogResult.OK)
{
newfirstname = ipfirst.answer;
}
else
{
this.Close();
}
}
Now, this.close() doesn't work at all.. so i used return; which stops it going on to ask for the last name and date of birth.. but i want it to stop asking questions (like return) AS WELL as close frmcustlist.
...
Thanks for any advice you can give.
ps. this appears in a few places, but is called in frmcustlist_load as well.. i dont know if that is going to make a difference or not!

Answer was made by STEVE in comments.
As frmcustlist was called itself as a Dialog, i just ended up having to give that dialog a Cancel result.
Final Code that works:
using (inputbox ipfirst = new inputbox("Enter Customer First Name:", "", ""))
{
if (ipfirst.ShowDialog() == DialogResult.OK)
{
newfirstname = ipfirst.answer;
}
else
{
DialogResult = DialogResult.Cancel;
return;
}
}

Related

Program not closing correctly c# and problems with forms

this is what of the errors I get when closing the program
then I'm closing the program it's not fully closing and it's still active in the background how I fix it?
and plus then switching forms ex:
this.Hide();
Form2 main = new Form2();
main.Show();
and going back it's showing again the check for updates message box
WebClient webClient = new WebClient();
if (!webClient.DownloadString("https://pastebin.com/raw/n77ayreS").Contains("1.6"))
{
if (MessageBox.Show("Looks like there is an available update, would you like to download it?", "Check For Updates", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
System.Diagnostics.Process.Start("https://github.com/TomerGamerTV/Unreal-Cracking-Pack/releases");
}
else
{
}
}
else
{
MessageBox.Show("You are on the latest version!", "Check For Updates");
}
this is my first time asking here so sorry if I did something wrong
Environment.Exit(0) is fixed the program thx Paul Sütterlin

C# Do While Message Box is active

I am working on a project in C# that requires user input from a pop-up message box.
I am also trying to have my code perform a series of tasks while the message box is active.
My goal is to have the MessageBox describe the tasks being performed and ask the user to observe and verify that they are being carried out.
I want these tasks to continuously be performed until the user clicks on a response in the MessageBox.
To create my message box, I am using:
MessageBox.Show(string <message>, string <caption>, MessageBoxButton.YesNo)
And the basic structure of what I am trying to do is as follows:
var userInput = MessageBox.Show("Are tasks A, B, C running?", "winCaption", MessageBoxButton.YesNo);
while (// <No response to MessageBox>)
{
// Task A
// Task B
// Task C
if (userInput == MessageBoxResult.Yes)
{
// PASS
// exit while loop
}
else
{
// FAIL
// exit while loop
}
}
I have found that when the MessageBox.Show() occurs & the pop-up window appears, the code seems to hang at that line until the user response is detected.
Is it possible to make this work? If not, are there any alternatives?
Thank you
How about calling MessageBox on separate Thread?
var action = new Action(() =>
{
var userInput = MessageBox.Show("Are tasks A, B, C running?", "winCaption", MessageBoxButtons.YesNo);
if (userInput == DialogResult.Yes)
{
// PASS
}
else
{
// FAIL
}
});
new Thread(new ThreadStart(action)).Start();
MessageBox.Show creates a modal dialog, meaning that execution on the thread stops until it is closed. You'll need to create a new Form that displays instead of using the built in MessageBox.
Once you've created the form, call it like this:
MyForm form = new MyForm();
form.Show(); //Note that this will NOT be modal
Keep in mind that Form does have a way to display it modally called ShowDialog(). It can be a bit confusing, so I'll summarize here:
MessageBox.Show(); //Modal
Form.Show(); //Not Modal
Form.ShowDialog(); //Modal

C# Stop the flow of the program and reset it without restarting

I am writing a simple WindowsForm program with radiobuttons, buttons, and a customary implemented InputBox.
Relevant program logic: I click one of the radiobutons from the groupbox -> enable button -> clicking button initiates custom inputbox asking for 1 value and Yes/Cancel buttons.
|
V
If Yes button clicked -> proceed with logic flow
If Cancel button clicked -> popup window appears ("Your input was cancelled, do you want to exit application?") with yes/no buttons
|
V
If Yes button clicked -> Exit the program
If No button clicked -> apply the same logic as if Reset button is clicked, which would reset the whole program without restarting it <---------This is what I am trying to achieve (all relevant methods are provided below)
What is the problem?
When I simply click Reset button, it applies all needed actions and stops, waiting for my further input. This is the exact result I am trying to achieve when I click No button in the popup window I mentioned above.
However, this is not the case. During the debug mode, after I clicked No button, it goes through the entire logic of the Reset button like I wanted, BUT right after that, it goes into the IF statement (marked in my buttonGetWorkHours_Click method). I don't want that, I want it to stop the flow after applying the logic of Reset button and waiting for my input (radiobutton/button click).
What I tried
I have searched through several threads here in SO and tried implementing several suggestions. The results of these suggestions are commented out inside inputBoxProcedure method. Also, I was looking for similar posts, which would give me the right idea. But they state that it is impossible without reloading. Based on that thread, I thought about implementing extra variable to use for checking if reset logic was running, but seems unnecessarily complicated.
ULTIMATE QUESTION:
I saw a test executable, so I know it is POSSIBLE, unlike what posts and threads were saying. Can you please point me in a right direction of how to proceed with it?
Relevant code snippet methods
For the sake of saving everyone's time I will include only methods relevant to my question.
private void buttonGetWorkHours_Click(object sender, EventArgs e)
{
if (radioButtonJobStatusFull.Checked)
{
inputBoxProcedure("Enter the total hours worked by the full time employee for the week", "40");
}
else if (radioButtonJobStatusPart.Checked)
{
inputBoxProcedure("Enter the total hours worked by the part time employee for the week", "30");
}
//if, else if, else, unrelated to the lines above
if() //<----------------the logic goes here after going through the whole Reset button logic
{}
else if()
{}
else()
{}
}
private void buttonReset_Click(object sender, EventArgs e)
{
//clear all radiobutton selections
//set all strings to empty
//disable several buttons and groupboxes
//hide several labels
}
private void inputBoxProcedure(string text, string defaulttext)
{
InputBoxResult result = InputBox.Show(text, "Hours Entry", defaulttext, new InputBoxValidatingHandler(inputBox_Validating));
if (result.OK)
{
labelHoursWorked.Text = result.Text.Trim();
}
else
{
if (MessageBox.Show("Input was cancelled. Do you wish to quit the application?", "Input Cancelled", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
Close();
}
else
{
buttonReset_Click(this, new EventArgs());
//Form fr = new Form();
//fr.Show();
//this.Close();
//Application.Restart();
}
}
}
Try changing the inputBoxProcedure to this:
private bool inputBoxProcedure(string text, string defaulttext)
{
InputBoxResult result = InputBox.Show(text, "Hours Entry", defaulttext, new InputBoxValidatingHandler(inputBox_Validating));
if (result.OK)
{
labelHoursWorked.Text = result.Text.Trim();
}
else
{
if (MessageBox.Show("Input was cancelled. Do you wish to quit the application?", "Input Cancelled", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
Close();
}
else
{
buttonReset_Click(this, new EventArgs());
//Form fr = new Form();
//fr.Show();
//this.Close();
//Application.Restart();
return false; // Added
}
}
return true; // Added
}
Notice that the return type void becomes bool and that two lines of return have been added.
In buttonGetWorkHours_Click change:
if (radioButtonJobStatusFull.Checked)
{
inputBoxProcedure("Enter the total hours worked by the full time employee for the week", "40");
}
else if (radioButtonJobStatusPart.Checked)
{
inputBoxProcedure("Enter the total hours worked by the part time employee for the week", "30");
}
Into:
if (radioButtonJobStatusFull.Checked)
{
if (!inputBoxProcedure("Enter the total hours worked by the full time employee for the week", "40"))
return;
}
else if (radioButtonJobStatusPart.Checked)
{
if (!inputBoxProcedure("Enter the total hours worked by the part time employee for the week", "30"))
return;
}
In this way, after a reset, the funtion inputBoxProcedure will return false. When the function returns false the function buttonGetWorkHours_Click will return and thus prevent further excecution.
I hope this helps.

How to open multiple chat forms with users separately, but block opening forms which already have been opened?

Prelude
At first, sorry for my bad english. :)
I read a tone of similar questions on SO, but none of them provide a solution for my problem, or I'm just stupid. :)
Question
How would I open a new chat form to talk with User1 and retain the possibility to open chat forms with other users from "users list", but block opening a chat form with a user which is already open?
I tried to find something for this, but whatever I tried, it always is same (I can open same form again and again).
So, for example, I can open a chat form with User1, I can talk with him, and I can also open a new chat form with User2 and I can talk with him. But I can also open multiple forms with User1, and with User2 to, etc.
Also, I need to pass some data from MainForm form to TalkForm, so as prototype I created this code and I tried to list, but I'm not sure how to check if a form does exist in the list:
List<TalkForm> b = new List<TalkForm>();
private void TextBoxConnectedClients_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (TextBoxConnectedClients.SelectedIndex == -1)
{
return;
}
int index = this.TextBoxConnectedClients.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
string username = TextBoxConnectedClients.SelectedItem.ToString();
TalkForm a = new TalkForm(im, username, displayname);
b.Add(a);
a.Show();
}
}
Can someone please give me some examples or tell me what I'm doing wrong? Thank you.
List<TalkForm> b = new List<TalkForm>();
You are using this list to track the forms opened for each unique user. I would update your code to check if form object is already added. You need to add using System.Linq
if (index != System.Windows.Forms.ListBox.NoMatches)
{
string username = TextBoxConnectedClients.SelectedItem.ToString();
// Check if form is already opened. Username will be unique.
var form = b.firstOrDefault(f => f.Username == username);
if (form == null) // Show new form
{
TalkForm a = new TalkForm(im, username, displayname);
b.Add(a);
a.Show();
}
else // Activate already opened form
{
form.BringToFront();
}
}
You need to expose TalkForm.Username property, if it's not in place already. And initialize that property in the constructor with username parameter.
Note: Make sure you Remove the form instance from list b when close a form for specific user.
Edit: Updated code to show already opened form as per #Draken's suggestion.

Make a check before closing form?

The code below is in MainFrame.cs and it opens and checks the MovieForm.cs. I want to check if a entered movie title already exist, before a new movie is added to a list. But the problem is, if the title already exist and the messagebox appears, then the MovieForm.cs is already closed and all other data gone and there is no possibilities for the user to change the title to another one! Could this be done in some other way that isn't to complicated? Is there a way to stop the closing of the form? Thanks!
private void btnNewMovie_Click(object sender, EventArgs e)
{
movieForm = new MovieForm();
if (movieForm.ShowDialog() == DialogResult.OK)
{
if (!movieManager.GetMovieFromList(index).Split(',') [0].Equals(movieForm.GetTitle))
{
movieManager.AddNewMovieToMediaLibrary(movieForm.GetNewMovie); // Anropar properties i objektet movieManager
UppdateListboxOfMovies();
}
else
{
MessageBox.Show("Det finns redan en film med titeln " + movieManager.GetMovieFromList(index).Split(',')[0], "Ooops!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
You have an opportunity to cancel the form closing:
private void btnNewMovie_Click(object sender, EventArgs e)
{
using (var movieForm = new MovieForm())
{
movieForm.Closing += (s, a) =>
{
if (movieForm.DialogResult == DialogResult.OK)
{
if (!movieManager.GetMovieFromList(index).Split(',') [0].Equals(movieForm.GetTitle))
{
movieManager.AddNewMovieToMediaLibrary(movieForm.GetNewMovie); // Anropar properties i objektet movieManager
UppdateListboxOfMovies();
}
else
{
MessageBox.Show("Det finns redan en film med titeln " + movieManager.GetMovieFromList(index).Split(',')[0], "Ooops!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
// Prevent the form from closing and let the user try again
a.Cancel = true;
}
}
};
movieForm.ShowDialog();
}
}
The movieForm object is still in scope, so you can still access any public data from it. I assume that movieForm.GetTitle is returning correctly. All you need to do now is apply the following correction because at the moment you are just comparing your title with the first title in the list:
if (!movieManager.GetMovieFromList(index).Split(',').Contains(movieForm.GetTitle))
...
That should solve your problem.
Edit: Ok, I misunderstood your problem. You want the form to stay open so that the user can make corrections. Possible solutions:
Solution 1: Pass in the movieManager object into MovieForm through a parameterized constructor. This way you can check the list before closing the form (on the button's click event).
Solution 2: Create a static MovieManager.GetMovieFromList method so that you aren't required to instantiate it.
I hope this makes sense.
You still have the movieForm object. You could do movieForm.ShowDialog() again.
Don't forget to fill in the edit fields again with the values in onShow or similar method.
Move the check/add code inside your MovieForm and then you can simply just call movieForm.ShowDialog(). You could also raise an event to the main form that the movie was added.

Categories

Resources