IF Not taking any decision? - c#

Look at this:
foreach(Object Item in comboBox1.Items)
{
if (Convert.ToString(Item) == Convert.ToString(dsGirasol.Tables["DatosGirasol"].Rows[contador][0]))
{
repetido = true;
break;
}
else
{
repetido = false;
}
}​
Note that both of the possible outputs have a messagebox. However when I run this, nothing appears at all, and the rest of the code continues to run...
EDIT: Added the surrounding loop!

Why do you want the break there for? Try this:
if (Convert.ToString(Item) == Convert.ToString(dsMaiz.Tables["DatosMaiz"].Rows[contador][0]))
{
repetido = true;
MessageBox.Show("Encontre uno igual");
}
else
{
repetido = false;
MessageBox.Show("Encontre uno diferente");
}

Try evaluating the left and right parts of the condition before you evaluate the equality.
I can only imagine that it must be throwing an exception that is silently caught.
This will help you debug the issue.
eg:
var left = Convert.ToString(Item);
var right = Convert.ToString(dsMaiz.Tables["DatosMaiz"].Rows[contador][0]);
if (left == right)
{
...
}
else
{
...
}
EDIT:
Now that I see you are using a loop, go back to basics, is the loop even running?
Low tech debugging, check that there are some Items in the combobox and that you are referencing the combo you intended :)

Ok this is strange, I managed to solve the problem by puting each loop on a separate method, and now it works, thanks for the help anyways!

Related

Fixing 'if'-'else' construct in C# Windows Forms

How do I do this? I have an if-else statement like this (not exact code but a symbolic idea):
if(formNull)
{
MessageBox.Show("empty")
}
else if(FormNotNull)
{
// I have validation if/elses here for input fields like
if(regex textbx1)
{
error
}
else
{
normal
}
if(regex textbx2)
{
error
}
else
{
normal
}
//Some more like this
} <<<<<<<<<<<< It stops here and never goes in the next 'else' statement even if the form is OK.
else
{
DBConn.myMethod(a, b, c, etc.)
if true
{
success!;
}
else
{
failed!;
}
}
I tried some nesting combinations, but nothing worked.
Seems like there's nothing left, as you already handled all cases in the if and else if.
if(formNull)
{
// goes here when `formNull` is true
}
else if(FormNotNull)
{
// goes here when `FormNotNull` is true and `formNull` is false
}
else
{
// goes here in any other case (but I guess there is no other case left)
}
That just means your two conditions (in the if and else if statements) are returning true. If either ever returns true, you will never go into your else block (both MUST be false).
Thank you all for suggestions. I simply used the separate textChanged events with Regex for errors and used simple if-statement like this
if (FormNull)
{
Message.Show("error");
}
else
{
DBConn.myMthod(a,b,c)
if(true)
{
sucess;
}
else
{
failed;
}
}
Just wanted to know the other option for what I was trying to do.

C# Error with 'continue'

I'm trying to use an if statement with a bool that will make it that if a code runs once it will not run again. Here is the code I am using.
int random = Program._random.Next(0, 133);
if (random < 33) {
bool done = false;
if(done)
{
continue; // Error is shown for this statement
}
Console.WriteLine("Not done!");
done = true;
}
The error that Visual Studio is displaying is: "No enclosing loop out of which to break or continue".
Depending on the class/method requirements, you could possibly reverse your logic:
if (!done)
{
Console.WriteLine("Not done!");
done = true;
}
You can't use a continue only inside a loop. So you must live without this:
int random = Program._random.Next(0, 133);
if(random < 33)
{
bool done = false;
if(!done)
{
Console.WriteLine("Not done!");
done = true;
}
}
In this case, you should reverse the if with if (!done) { ... }
You can't use continue like that, it can only be used in a loop. The continue statement will go to the end of the loop and continue with the next iteration, without a loop there is no end of the loop to go to.
You can use else instead:
if (done) {
// anything to do?
} else {
Console.WriteLine("Not done!");
done = true;
}
If there is nothing to do if the variable is true, you can just reverse the expression instead:
if (!done) {
Console.WriteLine("Not done!");
done = true;
}
Note: You need to store the variable done outside the scope. Now you have a local variable that is always set to false, so the code will never be skipped.
The exception is telling you that continue is ineffective here. It simply has nothing to do, and doesn't know where to continue. It is meant to be used within the iteration of a loop.

Solution to overused break statements?

I have a program that is completely functional, and I am now refactoring it. I am just in the process of learning c# so the original code was pretty terrible despite the fact that it ran just fine. One of the requirements of the program is that the user be able to return to the main menu at any point. I accomplished this as follows:
static bool bouncer = false
static void Exit(string input)
{
if (input == "\t")
{
bouncer = true
}
}
static string Prompt(string msg)
{
// takes input and passes it to Exit() then returns the input
}
static string FunctionA()
{
while(true)
{
if (bouncer == true)
{
break;
}
Prompt("whatever")
if (bouncer == true)
{
break;
}
Prompt("whatever")
if (bouncer == true)
{
break;
}
// return some stuff
}
}
static void Main()
{
bouncer = false
// writes the menu to console and handles UI
// FunctionA
{
The variable bouncer gets set to true if the user enters the "tab" character at any input point. The proliferation of break statement conditionals provides the structure that actually breaks out back to Main(). This is obviously not a very good solution and it makes the code hard to read.
Other attempts that I considered to accomplish the same task are:
Goto statement that jumps straight back to Main(). I scrapped this because goto has a very limited scope in c# and I don't think there is any good way to make it workable in this situation.
Calling Main() directly from Exit(). This is probably a bad idea, and I can't do it anyway because apparently Main() is "protected" in some way.
Using an event to react to TAB or ESC being pressed. It's unclear to me how I could use an event to do this since I still wouldn't be able to break right out of the event. My understanding is that the break statement has to actually be contained in the loop that needs to be broken as opposed to being written into a different function that is called from within the loop.
Any suggestions are greatly appreciated. I'm hoping there's something to be done with event handling or that I've overlooked something more simple. Thanks!
As a matter of coding style, the way it is works, but is seen as ugly. Unfortunately, if you need to break out immediately between sections of work, there is not a lot of ways around that.
You can change your current format of using breaks to using "if( bContinue ) { /* do next section of work */ }" control style. It changes the code from break out of the while loop to this:
static string FunctionA()
{
bool bContinue = true;
while( true == bContinue )
{
// Do initital work.
//
// Initial work can set bContinue to false if any error condition
// occurs.
if( true == bContinue )
{
// Do more work.
int returnCheck = MakeACall(); // Presume MakeACall returns negative interger values for error, 0 or positive values for success or success with condition/extra information.
if( 0 < returnCheck )
{
bContinue = false;
}
}
if( true == bContinue )
{
Prompt("whatever")
// Do more work.
bContinue = MakeASecondCall(); // Presume that MakeASecondCall returns true for success, false for error/failure
}
if( true == bContinue )
{
Prompt("whatever")
// Do more work.
// If error encountered, set bContinue to false.
}
if( true == bContinue )
{
Prompt("whatever else")
// Do more work.
// If error encountered, set bContinue to false.
}
// Done with loop, so drop out.
bContinue = false;
// return some stuff
}
}
Looking at your pseudo code, it reads like you only do a single pass through your work loop. If so, you can switch to a Do-While(false) format, and use the break to just drop to the bottom. Or, if you are only doing a single pass through your FunctionA, just do away with the While or Do-While control structure, and just use the if(true==bContinue){ /* Do more work */ }. It is not the cleanest of code, but when you perform long periods of serial work, you end up with such structures if you are not going to use a while or do-while for controlling the flow.
The disadvantage to using the if(bContinue){} style is that when an error condition occurs during the early stages of the process, the code does not exit out as quickly from the function as a break out of the while() or do-while() structure if the error occurs near the top of the work, as there will be the series of if statements that the code will test and then skip over. But it is readable, and if you use a descriptive name for your control variable (ie, nContinue or bContinue or workLoopControl) it should be fairly obvious that it is the master control flag for the function's work flow to whoever works or reviews the code after you.
Instead of an infinite loop and break statements, try using a conditional flag instead.
static void FunctionA()
{
bool done = false;
string response = string.Empty;
while (!done)
{
response = Prompt("whatever");
if(response == '\t')
{
done = true;
}
}
}
As a side note, I'm not sure why you have 'string' as the return type of several methods (e.g., 'FunctionA') when you aren't using the return value. That's why the code I gave above has it as 'void'.

Why doesn't my while loop in an async method stop?

I've got the following code in an async method in my app
b_saving = true;
while (b_saving == true)
{
try
{
if (1 == 1)
b_saving = false;
// anything down here should not execute?
i_should_not_run();
}
catch{
}
finally{
}
}
My expectation with this code is that it will stop as soon as b_saving is set to false. Yet when I run it, this is not the case. Breakpoints show the method continues on even when b_saving is false.
Do while loops not work this way in C#?
the loop will continue even after you set the b_saving to false, unless you put a break command in there, the while loop will continue executing until the end of its block and only then re-evaluate the condition and in this case most likely avoid another iteration of the loop, unless you set back b_saving to true inside your i_should_not_run method.
PS you can write a simpler condition in the while, no need to put the ==...
while (b_saving)
b_saving = true;
while (b_saving == true)
{
try
{
bool stop = true;
if (stop == true)
{
b_saving = false;
break;
}
// anything down here should not execute?
i_should_not_run();
}
catch{
}
finally{
}
}
You need to use break to stop execution like following
b_saving = true;
while (b_saving == true)
{
try
{
if (1 == 1){
b_saving = false;
break; // Will exit the loop
}
// anything down here should not execute?
i_should_not_run();
}
catch{
}
finally{
}
}
Read :
The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.
In order for the while loop to stop and not continue to execute the method your if statement should be like this:
if(1 == 1)
{
b_saving = false;
break;
}
The break keyword will exit the loop.
This has nothing to do with the async or the try/catch.
Setting b_saving to false is only part of the story - it has nil effect until you actually test its value and take an action based on that (in this case exit the while loop).
This is the way while loops always run.
You might also get interesting results from a compiler (depending on the language) - some of that code may get eliminated as it is effectively useless.
This loop should execute once as the first time b_saving == true. within the loop you set b_saving to false so it won't execute a second time.
To prevent i_should_not_run from being called add a break statement.
Few points:
The code above would complete the entire loop after setting the
m_saving flag to false, i you want it to stop right away you should
state it using the break keyword.
Judging by the name of the "m_saving" member you use, it's a local variable, therefore in a multithreaded scenario you should use read and write to it using atomic operation mechanisms.
Should the catch block be empty?
Just a template to consider
for{;;}
{
try
{
if(hasToStop)
{
break;
}
}
catch { hasToStop = true;}
}
Well it will carry on running for one run through the code, until the While check is carried out.
If you want to break out of the loop early then you want a break; statement.

What is the best way to avoid goto?

I usually fall into a situation where goto seems to be the best option to my mind. But I have read several times not to use it, and there is always an alternative. Now, I am trying something like this:-
try{
//Something that requires internet connectivity;
}
catch{
//Show a message-Internet connectivity lost,and go back to try
//-->FYI--Ignore "show message", because I am just appending this text to a
// textbox. So there won't be a problem of multiple ShowMessage Boxes.
}
Now, the best option seems to me is to use goto in catch statement, but I am trying to avoid it. try is the first statement in a function, and if I recall that function, I am piling up stacks, so thats not a better option as well. What alternative can I take?
Use a while loop with a flag
var tryAgain = true;
while (tryAgain)
{
try
{
...
tryAgain = false;
}
catch (...)
{
tryAgain = ...
}
}
In this particular case there is nothing wrong with calling the same function recursively and keeping a counter with the number of times you've called it. Something like this (in pseudo code):
public void DoMyInternetThing(int numberOfAttemptsRemaining)
{
try
{
//do stuff
}
catch (ConnectionException)
{
if (numberOfAttemptsRemaining <= 0)
throw new SomethingBadHappenedException();
DoMyInternetThing(numberOfAttemptsRemaining - 1);
}
}
As with anything recursive you need to ensure you structure it correctly, but this works nicely (I've used it myself) and it avoids your goto (which is not bad in itself, but use of it can lead to spaghetti or badly structured code).
If you want to try again, wrap your try-catch in a do-while loop.

Categories

Resources