hello I need a solution to my problem
How can I go to another if
When his work ends
It does not operate if number 2
To when the first is completed
I also want to jump over it to complete the rest of the code
I have used ( goto )
But it didn’t work. I don’t know what to do in this case. Please help me, thank you
if (listBox3.Items[m].ToString() == errorMessage2)
{
writerWCC.WriteLine(data[i]);
listBox2.Items.Add(data[i]);
break;
}
}
///////////////// i need go here after found error message in first (if)
{
if (listBox3.Items[m].ToString() == errorMessage2)
{
writerWCC.WriteLine(data[i]);
listBox2.Items.Add(data[i]);
}
}
Thread.Sleep(7000);
writerCCC.WriteLine(data[i]);
if (address != Clipboard.GetText())
{
DialogResult dialogResult = MessageBox.Show("Do you want to save this error ?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, MessageBoxOptions.DefaultDesktopOnly);
if (dialogResult == DialogResult.Yes)
{
writerWCC.WriteLine(data[i]);
writerWCC.Close();
writerCCC.Close();
Process.GetCurrentProcess().Kill();
}
else if (dialogResult == DialogResult.No)
{
listBox1.Items.Add(data[i]); break;
}
}
else
{
listBox1.Items.Add(data[i]);
}
}
writerWCC.Close();
writerCCC.Close();
MessageBox.Show("Execution is complete.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
}
else
{
MessageBox.Show("Input Files are not selected.");
}
}
As Mono and HimBromBeere already mentioned, your question is a bit difficult to understand, but I will try anyway.
It seems like your want to know later in your code, if a certain error message was found. You can simply remember this in a bool variable, for example:
bool errorMessage2WasFound = false;
for (int m = 0; m < listBox3.Items.Count; m++)
{
if (listBox3.Items[m].ToString() == errorMessage2)
{
writerWCC.WriteLine(data[i]);
listBox2.Items.Add(data[i]);
errorMessage2WasFound = true;
break;
}
}
if (errorMessage2WasFound)
{
// do what you want to do in this case
}
Related
I have this (if-else if-else) statement it works fine except the else part I don't know why ?
void TakeAction()
{
try
{
if (chkProduct.Checked == true && chkMaterial.Checked == false)
{
InsertProduct();
MessageBox.Show("Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
else if (chkProduct.Checked == false && chkMaterial.Checked == true)
{
InsertMaterial();
MessageBox.Show("Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
else if (chkProduct.Checked == true && chkMaterial.Checked == true)
{
InsertSubProduct();
MessageBox.Show("Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
// else if (chkProduct.CheckState == CheckState.Unchecked && chkMaterial.CheckState == CheckState.Unchecked) // Tried this also still nothing
else
//Doesn't work
{
MessageBox.Show("Check even one Checkbox", "Choose", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception Err)
{
MessageBox.Show("This Error Occured :" + Err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I tried different ways like just else , else if And finally the commented line in code .
Thanks in advance.
Edit#1
I think this method interferes with the TakeAction method and causes the problem , I will debug my code from the start , Thanks
if (chkProduct.Checked == true && chkMaterial.Checked == false)
{
da = new SqlDataAdapter("SELECT [ProductCode] FROM Products Where [ProductCode] = #prcode ", Cn);
da.SelectCommand.Parameters.AddWithValue("#prcode", txtcode.Text);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//int cnt = Convert.ToInt32(dt.Rows[0]["ProductCode"].ToString());
MessageBox.Show("Duplicated", "Duplicated");
}
else
{
//MessageBox.Show("No problem , Its not Product");
TakeAction();
}
}
//the first If >> If Material Or SubProduct
else if (chkMaterial.Checked == true)
{
da = new SqlDataAdapter("SELECT Code FROM Items Where Code = #prcode ", Cn);
da.SelectCommand.Parameters.AddWithValue("#prcode", txtcode.Text);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Duplicated", "Duplicated");
}
else
{
// MessageBox.Show("No problem , Its not item");
TakeAction();
}
You have 4 different combinations in total:
chkProduct.Checked : chkMaterial.Checked : Action
--------------------------------------------------------------
true : true : InsertSubProduct()
true : false : InsertMaterial()
false : true : InsertProduct()
false : false : Ask User to Check
That's why you don't have to put the last condition as else if: else is enough. If you have problems with debugging you can change the code into nesting ifs and push the last condition forward:
if (!chkProduct.Checked && !chkMaterial.Checked)
MessageBox.Show("Check even one Checkbox",
"Choose",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
else {
if (chkProduct.Checked)
if (chkMaterial.Checked)
InsertSubProduct();
else
InsertProduct();
else
InsertMaterial();
MessageBox.Show("Done",
"Done",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
Close();
}
If the else statement doesn't work it means that one of the else if statements is being hit. Have you tried breakpointing? You can also remove the true and false values to make it more readable.
Instead of:
if (x == true && y == false) { }
You can do the following:
if (x && !y) { }
I wrote nested if statement. One of them includes a loop. After this loop else statement does not work As if they did not exist. It goes to catch statement.
Although when I cancel this loop, else statement work.
How can I fix it?
This is visual studio and SQL Server 2005. I have tried to save the value what in the text box "txtCategoryName". In the first if statement I check that text box is not null. In the second "if statement" I check the value what in the text box duplicate or not. In the else statement, I save the value.
try
{
if (txtCategoryName.Text == string.Empty)
{
MessageBox.Show("Fill the textBox", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else if (txtCategoryName.Text != string.Empty)
{
for (int i = 0; i <= dgvCategory.Rows.Count; i++)
{
if (dgvCategory.Rows[i].Cells[1].Value.ToString() == txtCategoryName.Text)
{
MessageBox.Show("Choose another name", "", MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
return;
}
}
}
else
{
txtCategoryId.Text = clsCat.getCategoryId().Rows[0][0].ToString();
clsCat.addCategory(txtCategoryName.Text);
MessageBox.Show("Done", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCategoryId.Clear();
txtCategoryName.Clear();
dataPreview();
}
}
catch
{
MessageBox.Show("Erroe save in category", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
I expect to save "txtCategoryName.Text" in the database if it pass through the first "if statement" and the second "if statement" to do what in "else statement". But after the loop in the second "if statement" it goes to "catch" directly.
The problem is in int i = 0; i <= dgvCategory.Rows.Count; i++ because you are initializing the i with 0 and go through dgvCategory.Rows.Count.
It should be int i = 0; i < dgvCategory.Rows.Count; i++ more specifically i < dgvCategory.Rows.Count; instead of i <= dgvCategory.Rows.Count;
Just add one isElseLoop bool variable which will get updated once the else loop is executed. Refer the code below.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
bool isElseLoop = false;
if (txtCategoryName.Text == string.Empty)
{
MessageBox.Show("Fill the textBox", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else if (txtCategoryName.Text != string.Empty)
{
for (int i = 0; i < dgvCategory.Rows.Count; i++)
{
if (dgvCategory.Rows[i].Cells[1].Value.ToString() == txtCategoryName.Text)
{
MessageBox.Show("Choose another name", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
isElseLoop = true;
return;
}
}
}
if (!isElseLoop)
{
txtCategoryId.Text = clsCat.getCategoryId().Rows[0][0].ToString();
clsCat.addCategory(txtCategoryName.Text);
MessageBox.Show("Done", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCategoryId.Clear();
txtCategoryName.Clear();
dataPreview();
}
}
catch
{
MessageBox.Show("Erroe save in category", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
I want after Message Box show
prevent data from insert to DB
int numberOfRecords = Convert.ToInt32(qotext.Text);
if (numberOfRecords == 9999)
{
MessageBox.Show("try other value", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
You need something like:
if (conditionToNotInsert) {
MessageBox.Show(...);
} else {
InsertStuffIntoDb();
}
The else block is only executed if the condition of the if is not true.
I have to validate the textboxes to check if they are a number and if they are in the database. Only problem is I can only seem to get it to check for validity or if they are numeric. How can change this to get both validations?
it validates to make sure there is something in the textboxes:
if (string.IsNullOrEmpty(employeeIDTextBox.Text) && (string.IsNullOrEmpty(JobIDTextBox.Text)))
Then it looks to see if the value is numeric, then if it does it checks to see if the person exists, then sets the values
else if (string.IsNullOrEmpty(JobIDTextBox.Text))
{
if (!Int32.TryParse(JobIDTextBox.Text, out number1))
{
using (dbConn)
{
ReportGrid newGrid = new ReportGrid();
if (newGrid.isValidEmp(Int32TryParseSafe(employeeIDTextBox.Text)))
{
newGrid.startDate = startingdateTimePicker.Value;
newGrid.endDate = endingdateTimePicker.Value;
newGrid.EmployeeID = Int32TryParseSafe(employeeIDTextBox.Text);
newGrid.JobID = Int32TryParseSafe(JobIDTextBox.Text);
newGrid.ShowDialog();
}
else
{
MessageBox.Show("No ID found for the employee.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
Then it does the same for the other textbox
else if (string.IsNullOrEmpty(employeeIDTextBox.Text))
{
if (!Int32.TryParse(emplyeeIDLabel.Text, out number2))
{
using (dbConn)
{
ReportGrid newGrid = new ReportGrid();
if (newGrid.isValidJob(Int32TryParseSafe(JobIDTextBox.Text)))
{
newGrid.startDate = startingdateTimePicker.Value;
newGrid.endDate = endingdateTimePicker.Value;
newGrid.EmployeeID = Int32TryParseSafe(employeeIDTextBox.Text);
newGrid.JobID = Int32TryParseSafe(JobIDTextBox.Text);
newGrid.ShowDialog();
}
else
{
MessageBox.Show("No ID found for that job.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
MessageBox.Show("Must be a number.");
}
Here is the whole code
try
{
if (string.IsNullOrEmpty(employeeIDTextBox.Text) && (string.IsNullOrEmpty(JobIDTextBox.Text)))
{
MessageBox.Show("Please enter a EmployeeID or JobID.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (string.IsNullOrEmpty(JobIDTextBox.Text))
{
if (!Int32.TryParse(JobIDTextBox.Text, out number1))
{
using (dbConn)
{
ReportGrid newGrid = new ReportGrid();
if (newGrid.isValidEmp(Int32TryParseSafe(employeeIDTextBox.Text)))
{
newGrid.startDate = startingdateTimePicker.Value;
newGrid.endDate = endingdateTimePicker.Value;
newGrid.EmployeeID = Int32TryParseSafe(employeeIDTextBox.Text);
newGrid.JobID = Int32TryParseSafe(JobIDTextBox.Text);
newGrid.ShowDialog();
}
else
{
MessageBox.Show("No ID found for the employee.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
MessageBox.Show("Must be a number.");
if (startingdateTimePicker.Value > endingdateTimePicker.Value)
{
MessageBox.Show("Starting data can not be after than ending date.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else if (string.IsNullOrEmpty(employeeIDTextBox.Text))
{
if (!Int32.TryParse(emplyeeIDLabel.Text, out number2))
{
using (dbConn)
{
ReportGrid newGrid = new ReportGrid();
if (newGrid.isValidJob(Int32TryParseSafe(JobIDTextBox.Text)))
{
newGrid.startDate = startingdateTimePicker.Value;
newGrid.endDate = endingdateTimePicker.Value;
newGrid.EmployeeID = Int32TryParseSafe(employeeIDTextBox.Text);
newGrid.JobID = Int32TryParseSafe(JobIDTextBox.Text);
newGrid.ShowDialog();
}
else
{
MessageBox.Show("No ID found for that job.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
MessageBox.Show("Must be a number.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I could be mistaken but is this line possibly the problem?
if (!Int32.TryParse(emplyeeIDLabel.Text, out number2))
The exclamation point reverses the bool so if the text successfully parses as a number the TryParse function returns true but by using the exclamation the if statement resolves to false. Therefore you are sending the code to else statement which states that it is not a number.
Also, try using "Return" to avoid nested ifs.
if (string.IsNullOrEmpty(employeeIDTextBox.Text) && (string.IsNullOrEmpty(JobIDTextBox.Text)))
{
MessageBox.Show("Please enter a EmployeeID or JobID.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Return;
}
There's no need for an else at this point because the if the if statement resolves to true you will return from the method.
Nested if statements are frequently necessary but they should be avoided when they can to make code clearer to read for maintenance.
I have a MessageBox.Show event that I want to also prevents timer-based methods from running while the MessageBox remains open.
Here is my code (Changes the value in a file location on a network every x minutes):
public void offlineSetTurn()
{
try
{
using (StreamWriter sWriter = new StreamWriter("FileLocation"))
{
sWriter.WriteLine(Variable);
}
}
catch (Exception ex)
{
DialogResult result = MessageBox.Show("Can't find file. Click Okay to try again and Cancel to kill program",MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
offlineSetTurn();
}
else if (result == DialogResult.Cancel)
{
Application.Exit();
}
}
}
I have methods in the form that are calling this every thirty seconds. Meaning every thirty seconds, another MessageBox pops up. Is there a way to pause the application with MessageBox and if not, what would be the best way to resolve this issue? If possible, I'd like to avoid using Timer.Stop() as it would reset the Timer count.
The simplest solution is to have a flag indicating whether or not the message box is currently open:
private bool isMessageBoxOpen = false;
public void offlineSetTurn()
{
if (isMessageBoxOpen)
return;
try
{
using (StreamWriter sWriter = new StreamWriter("FileLocation"))
{
sWriter.WriteLine(Variable);
}
}
catch (Exception ex)
{
isMessageBoxOpen = true;
DialogResult result = MessageBox.Show("Can't find file. Click Okay to try again and Cancel to kill program",MessageBoxButtons.OKCancel);
isMessageBoxOpen = false;
if (result == DialogResult.OK)
{
offlineSetTurn();
}
else if (result == DialogResult.Cancel)
{
Application.Exit();
}
}
}