-2

I need to check if an input is valid prior to updating my db.

I have created a bool method to check if it is valid.

private bool validProject(string ProjectID)
{
    using (AXEntitiesDEV db = new AXEntitiesDEV())
    {
        return db.PROJTABLEs.Any(c => c.PROJID==ProjectID);

    }
}

and am checking it in my update method.

 protected void Insert(object sender, EventArgs e)
    {
        using (GPSE2Entities entities = new GPSE2Entities())
        {
            TextBox txtEditTime = (TextBox)gvDailyGPS.FooterRow.FindControl("txtFooterTime");
            DropDownList ddlEventDateOnly = (DropDownList)gvDailyGPS.FooterRow.FindControl("ddlFooterDateOnly");
            DateTime EDT = DateTime.Now;
            TextBox txtAddProjectID = (TextBox)gvDailyGPS.FooterRow.FindControl("txtAddProjectID");
            validProject(txtAddProjectID.Text);
            DailyGPSTable newLOB = new DailyGPSTable
                {
                    EventDateTime = EDT,
                    Project = txtAddProjectID.Text,
                };

                entities.DailyGPSTables.Add(newLOB);
                {
                    entities.SaveChanges();
                    BindGrid();
                }
                entities.SaveChanges();
            }
    }

I tried catching and reporting the error but it allows invalid input through when false.

try
{
    validProject(txtAddProjectID.Text);
}
catch (ArgumentException)
{
    addErr.Text = "";

    addErr.Text = "Invalid Project ID.";
}

What's the best way I can catch and report the error prior to trying the insert?

  • 3
    Why do you want to throw a costly exception when you could simply get the return value and set the error text without any problem? – Steve Nov 20 '18 at 20:21
  • 2
    This appears to be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Nkosi Nov 20 '18 at 20:23
  • I need to stop processing a db insert if this condition (one of many) is true. – Doug Farrell Nov 20 '18 at 20:26
  • 1
    Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [ask] page for help clarifying this question. – Nkosi Nov 20 '18 at 20:31
  • 1
    @DougFarrell until you better explain the actual problem with a [mcve], those trying to help you wont be able to properly address the issue. – Nkosi Nov 20 '18 at 20:33
  • I was seeking a quick answer as I am pressed for time and leaving the office. I will return to verify and elaborate on the issue if need be or use one of the answers posted here. Please no more downvotes. Or should I simply delete it? – Doug Farrell Nov 20 '18 at 20:38
  • @DougFarrell You can't delete a question that has an upvoted answer. You are better off fixing the question. That is what is attracting the negative votes. – Nkosi Nov 20 '18 at 20:53
  • @Nkosi I updated the question. – Doug Farrell Nov 20 '18 at 21:32
  • @DougFarrell this is much clearer than the original post and looks like it is addressed by JoelCoehoorn answer. – Nkosi Nov 20 '18 at 21:35

3 Answers3

3

You can throw your own exception:

try
{
    if (!validProject(txtAddProjectID.Text))
        throw new ArugmentExceptioN(txtAddProjectID.Text);
}
catch (ArgumentException)
{
    addErr.Text = "";
    addErr.Text = "Invalid Project ID.";
}

But don't do that!

You already have a boolean telling you the function failed. Just use that with a normal if block:

if (!validProject(txtAddProjectID.Text))
{
    addErr.Text = "";
    addErr.Text = "Invalid Project ID.";
}

this is only one of many conditions that must be met prior to updating the db

There's still no need for an exception.

bool validRecord = true;

validRecord = validRecord && validProject(txtAddProjectID.Text);
validRecord = validRecord && someOtherCheck();
validRecord = validRecord && someFinalCheck();
validRecord = validRecord && howEverManyYouNeed();

if (!validRecord)
{
    ShowError();
}
else
{
    UpdateDB();
}

You can do a similar thing by just appending to a string or adding to a list that starts out empty. At the end, if the item has any length, show the errors.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Yes but this is only one of many conditions that must be met prior to updating the db – Doug Farrell Nov 20 '18 at 20:31
  • Joel, Thanks for the answer I will try it and let you know the results. And just for my information can you please tell my why this is superior to throwing an exception? – Doug Farrell Nov 20 '18 at 21:41
  • @DougFarrell exceptions are expensive and should actually only be thrown for exceptional circumstances (pun intended). check this post https://stackoverflow.com/questions/891217/how-expensive-are-exceptions-in-c – Nkosi Nov 20 '18 at 21:48
0
try
{
  validProject(txtAddProjectID.Text);
}
catch (ArgumentException e)
{
  addErr.Text = "";

  addErr.Text = e.Message;
}


private static void validProject(object text)
{
  throw new ArgumentException($"Invalid Project ID.{text}");
}
Ryan Schlueter
  • 2,223
  • 2
  • 13
  • 19
  • This throws the exception every time `validProject()` is called. The OP asked for it to throw an exception only when `validProject()` returns `false`. – Lews Therin Nov 20 '18 at 20:26
0

Just check the result of the call to validProject and throw an exception if it returns false:

try
{    
    if (!validProject(txtAddProjectID.Text))
        throw new ArgumentException("Argument is invalid", nameof(txtAddProjectID.Text));
}
catch (ArgumentException)
{
    addErr.Text = "";

    addErr.Text = "Invalid Project ID.";
}
Lews Therin
  • 3,707
  • 2
  • 27
  • 53