How to fix this "for loop" what in if statement - c#

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

Related

Why my methods interfering with each others and with if statements in C#?

I have a form to insert some data in sql database with some conditions , First I need to check for nulls and alert the user :
void CheckNulls() {
try {
if (txtcode.Text.Length == 0 || txtItem.Text.Length == 0 || txtWh.Text.Length == 0) {
MessageBox.Show("Fill Required Fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else {
checkExistAndDo();
}
}
catch(Exception Err) {
MessageBox.Show("This Error Occured :" + Err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Then I need to check if the user checked any checkbox :
void checkExistAndDo() {
if (chkProduct.Checked || chkMaterial.Checked)
{
if (chkProduct.Checked == true) {
if (!chkMaterial.Checked) {
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) {
MessageBox.Show("Existing Code", "Error");
}
else {
TakeAction();
}
}
}
else {
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("Existing Code", "Error");
}
else {
TakeAction();
}
}
}
else {
MessageBox.Show("Check even one", "check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
So , I have 4 different combinations in total :
chkProduct.Checked : chkMaterial.Checked : Action
--------------------------------------------------------------
true : true : InsertSubProduct()
true : false : InsertProduct()
false : true : InsertMaterial()
false : false : Ask User to Check
Then I need to take action based on the combination :
private void TakeAction()
{
try
{
if (chkProduct.Checked == true && chkMaterial.Checked == false)
{
InsertProduct();
MessageBox.Show("Product Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (chkProduct.Checked == false && chkMaterial.Checked == true)
{
InsertMaterial();
MessageBox.Show("Material Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
InsertSubProduct();
MessageBox.Show("SubProduct Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception Err)
{
MessageBox.Show("This Error Occured :" + Err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
this.Close();
}
}
The problem is that this part doesn't do anything not showing my message , Not even an error message as if it doesn't exist in my code :
else
{
InsertSubProduct();
MessageBox.Show("SubProduct Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Sorry for long post but i tried my best and debugged the code many times and i can't get pass this , Thanks in advance and your help is deeply appreciated .
If the ThreeState property is set to true, the Checked property will return true for either a Checked or Indeterminate CheckState.
Check the ThreeState property for chkMaterial checkbox
Based on #Joel Coehoorn comments I tried different approach
I quote " Do separation of concerns better. CheckNulls() should only return a bool, and not show any messages to the user or call any other methods. checkExistAndDo() should not exist at all (that logic should be entirely in the database as part of InsertProduct/MaterialSubproduct()). "
It worked great , Thanks all for replying , I appreciate your guiding .

Why this last condition else doesn't work properly C#

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) { }

need with if Stopping method first if to if number tow

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
}

prevent data from add to db after Message Box

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.

Performing multiple validations on one field C#

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.

Categories

Resources