Cant find the issue in this loop - c#

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.

Related

If statement skips the elements except the first one in the for loop. How can I get the right solution for the other elements?

for (int i = 0; i < dt.Rows.Count; i++)
{
if (textBox1.Text == dt.Rows[i]["FIRSTNAME"].ToString().ToLower() && textBox2.Text == dt.Rows[i]["LASTNAME"].ToString().ToLower())
{
Main ss = new Main(); // Main is the another form which is seen after the successful enterance.
ss.Show();
break;
}
else {
MessageBox.Show("UserName or Password is Wrong");
}
}
I want to create a Windows form application using C# and PL/SQL database. I have a data information which consists of the FÄ°RSTNAME and LASTNAME of the two persons. Because of the for loop, I get both of the success and the failure messages at the same time for the second person's information. When for loop cannot match the second person's information with the first person's information, it shows the failure message. Then it sees right information. So, it returns the true message to me.
How can I return the beginning of the if statement to get the all solutions until the end of the database? I put the else statement's codes out of the for loop. I got always the failure message because of the non-existing the if statement to Control the failure.
Shortly, what do I need to do?
Lot of conceptual errors. The else statements is not out of the loop!
You need a flag to check if you have found or not the person in the loop. Then check this flag out of the loop.
bool found = false;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (textBox1.Text == dt.Rows[i]["FIRSTNAME"].ToString().ToLower() && textBox2.Text == dt.Rows[i]["LASTNAME"].ToString().ToLower())
{
found = true;
break;
}
}
if (found)
{
Main ss = new Main(); // Main is the another form which is seen after the successful enterance.
ss.Show();
}
else
{
MessageBox.Show("UserName or Password is Wrong");
}
You can change this to Linq:
if (dt.AsEnumerable().Any( // Check if there is any row meeting criteria
r => r.RowState != DataRowState.Deleted && // row should not be deleted
r.Field<string>("FIRSTNAME").Equals(textBox1.Text, StringComparison.CurrentCultureIgnoreCase) && // First name matches ignoring case
r.Field<string>("LASTNAME").Equals(textBox2.Text, StringComparison.CurrentCultureIgnoreCase))) // Last name matches ignoring case
{
Main ss = new Main(); // Main is the another form which is seen after the successful enterance.
ss.Show();
}
else
{
MessageBox.Show("UserName or Password is Wrong");
}

how to save an ID if the you leave the name empty?

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.

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.

Getting data from ms access database using reader properly

Good day sir! I able to call a data from my database using reader and after getting a data in the database their will be a messageBox appear when I get my expected data. Here's my sample code:
if (textBox5.Text == "")
{ }
else
{
DialogResult ms = MessageBox.Show("Try Again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
if (ms == DialogResult.OK)
{
textBox5.Clear();
textBox1.Clear();
listBox5.Items.Clear();
textBox3.Clear();
listBox4.Items.Clear();
}
}
while (reader.Read())
{
listBox4.Items.Clear();
if (string.Compare(label1.Text, reader.GetString(0)) == 0)
{
for (int t = 1; t < 11; t++)
{
words.Add(reader.GetString(t));
}
}
words.Shuffle();
listBox4.Items.AddRange(words.ToArray());
}
reader.Close();
coon.Close();
My problem here is when I apply these codes, there are two messageBox will appear so I remove this codes :
textBox5.Clear();
textBox1.Clear();
listBox5.Items.Clear();
textBox3.Clear();
listBox4.Items.Clear();
all I want is I want to show the messageBox once. Can u help me with this?
You have not shown enough code, but I'm going to assume this function is inside a TextChanged event.
If that is the case, you're checking if TextBox5 has some text, then you're clearing a number of controls on the form. You haven't shown other events and what they do, so it would be hard to tell you more at this point.
Consider debugging your code and stepping through it line by line, that way you can follow the logic of the program flow and see where the hiccup occurs...
I'd also change the first 3 lines:
if (textBox5.Text == "")
{ }
else
with if (!string.IsNullOrEmpty(this.textBox5.Text.Trim())), which means, if string is not empty (null or empty to be precise).
Hope this helps.
Good luck

C# if statement true cancel the remaining process

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();
}
}
}

Categories

Resources