1

I am checking for duplicates and it finds them and the If(isDuplicate) all works fine. But the code continues and does all the submit because I am not telling it to stop. How would I do this ? to stop and throw the error panel which it does but not submit?

_db.tbl_Localities.InsertOnSubmit(locality);

bool isDuplicate = _db.tbl_Localities
                    .Any(x => x.Locality == txt_Locality.Text);
if (isDuplicate)
{
    pnl_Message.Visible = true;
    lbl_message.Text = " Duplicate entry!";
    txt_Locality.Text = "";
}

// Save
// ====
_db.SubmitChanges();
StudentRik
  • 1,049
  • 2
  • 20
  • 37

2 Answers2

3

You should handle else part of condition, or raise an exception if it's unexpected situation for your program:

_db.tbl_Localities.InsertOnSubmit(locality);

bool isDuplicate = _db.tbl_Localities
                    .Any(x => x.Locality == txt_Locality.Text);
if (isDuplicate)
{
    pnl_Message.Visible = true;
    lbl_message.Text = " Duplicate entry!";
    txt_Locality.Text = "";
}
else
{
    // Save
    // ====
    _db.SubmitChanges();
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

Use return; in the if statement.

Kasper Cottaar
  • 462
  • 3
  • 14
  • I would never advise using return statements other than at the end of a function. They can be easily overlooked when trying to maintain code and make it much harder to refactor code at a later date. – Justin Harvey Feb 28 '13 at 11:21
  • @JustinHarvey well I think there lot of situations where `return` is appropriate. E.g. guard conditions, or returning from switch statements – Sergey Berezovskiy Feb 28 '13 at 11:23
  • @JustinHarvey you're probably correct here. I'm currently working in some code where they held to that believe. It only created nested if statements 10 levels deep, ther might be another problem here ;). Using return in a void espacially it's something to do with validation is better then nesting your if statements in my eyes. [Is it bad practice to use return inside a void method?](http://stackoverflow.com/questions/1283325/is-it-bad-practice-to-use-return-inside-a-void-method) – Kasper Cottaar Feb 28 '13 at 11:28
  • @lazyberezovsky, neither of your examples are an excuse in my view. – Justin Harvey Feb 28 '13 at 11:31
  • @Justin in my opinion the real problem is when you can't see all of the function in one screen. In cases where the function is well refactored I haven't had your problem. – Aron Feb 28 '13 at 11:38
  • @Aron, it sounds like you might be in trouble then if the function is more than one screen and not properly re-factored (as if that could ever happen). – Justin Harvey Feb 28 '13 at 12:09