1

私はtry/catchを書こうとしていますが、明らかに失敗しています。try/catch を完全に理解しているかどうかはわかりませんが、正しい日付がフォームから送信されていることを確認するために必要なことに頭を悩ませていることは知っています。つまり、文字列ではなく DateTime 形式である必要があり、(MM/dd/yyyy) である必要があると収集しますが、この試行/チェックが原因でループが発生します。

手順: frmPersonnel コードに追加した検証コードに戻り、ロジックを含む try/catch を追加して、無効な日付が原因でサーバー エラーが発生しないようにします。

コード:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class frmPersonnel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSubmit.Click += new EventHandler(this.btnSubmit_Click);//event for button
    }

    private void btnSubmit_Click(object sender, EventArgs e)
    {
//DECLARATIONS
        int count = 0;
        string Msg = "You must enter a value in the following fields: <br/>  ";
        Boolean validatedState = true;
        Boolean validateEntry = false;
        DateTime endDate = new DateTime(2016, 03, 01);
        DateTime startDate = new DateTime(2016, 03, 01);


//BEGIN SERIES OF IF/ELSE FOR CONFIRMING ENTRIES         
        if (Request["txtFirstName"].ToString().Trim() == "")
            {
            //displays yellow bg for missing input
            txtFirstName.BackColor = System.Drawing.Color.Yellow;
            Msg = Msg + "First Name <br/> ";
            }//endif
        else
        {
            txtFirstName.BackColor = System.Drawing.Color.White; 
            count += 1;
        }//end else

        if (Request["txtLastName"].ToString().Trim() == "")
        {
            //displays yellow bg for missing input
            txtLastName.BackColor = System.Drawing.Color.Yellow;
            Msg = Msg + "Last Name <br/> ";
        }//endif
        else
        {
            txtFirstName.BackColor = System.Drawing.Color.White; 
            count += 1;
        }//end else

        if (Request["txtPayRate"].ToString().Trim() == "")
        {
            //displays yellow bg for missing input
            txtPayRate.BackColor = System.Drawing.Color.Yellow;
            Msg = Msg + "Pay Rate <br/>  ";
         }//endif
        else
        {
            txtFirstName.BackColor = System.Drawing.Color.White; 
            count += 1;
        }//end else

        if (Request["txtStartDate"].ToString().Trim() == "")
        {
            //displays yellow bg for missing input
            txtStartDate.BackColor = System.Drawing.Color.Yellow;
            validateEntry = false;
            Msg = Msg + "Start Date <br/>  ";
        }//endif
        else
        {
            try
                {
                //Conversion to DateTime format?
                startDate = DateTime.Parse(Request["txtStartDate"]);
                //How do I write the format I want, and when it should be checked?
                }
            catch (Exception ex)
                {
                //Exception should be caught here, not sure how to write this out though?
                }
            validateEntry = true;
        }//end else

        if (Request["txtEndDate"].ToString().Trim() == "")
        {
            //displays yellow bg for missing input
            txtEndDate.BackColor = System.Drawing.Color.Yellow;
            validateEntry = false;
            Msg = Msg + "End Date <br/>  ";
         }//endif
        else
        {
            try
            {
                //Conversion to DateTime format?
                endDate = DateTime.Parse(Request["txtEndDate"]);
                //How do I write the format I want, and when it should be checked?
            }
            catch (Exception ex)
            {
                //Exception should be caught here, not sure how to write this out though?
            }
            validateEntry = true;

        }//end else
//END SERIES OF IF/ELSE FOR CONFIRMING ENTRIES 

//START IF VALIDATE ENTRY    
        if (validateEntry == true)
        {
            if (DateTime.Compare(startDate, endDate) >= 0)
            {
                txtStartDate.BackColor = System.Drawing.Color.Yellow;
                txtEndDate.BackColor = System.Drawing.Color.Yellow;
                Msg = Msg + "Start Date <br/>" + "End Date <br/> <br/>The end date must be a later date than the start date.";
                //The Msg text will be displayed in lblError.Text after all the error messages are concatenated
                validatedState = false;
                //Boolean value - test each textbox to see if the data entered is valid, if not set validState=false. 
                //If after testing each validation rule, the validatedState value is true, then submit to frmPersonnelVerified.aspx, if not, then display error message
            }
            else //goes to this if dates are correct
            {
                validatedState = true;
                count += 2;
                txtStartDate.BackColor = System.Drawing.Color.White;
                txtEndDate.BackColor = System.Drawing.Color.White;
            }
        }
//END IF VALIDATE ENTRY

//SENDS DATA & ERROR MESSAGES
        if (count == 5 && validatedState == true)
        {
            Session["txtFirstName"] = txtFirstName.Text;
            Session["txtLastName"] = txtLastName.Text;
            Session["txtPayRate"] = txtPayRate.Text;
            Session["txtStartDate"] = txtStartDate.Text;
            Session["txtEndDate"] = txtEndDate.Text;
            Response.Redirect("frmPersonnelVerified.aspx");
            //sends to other page
        }
        else
        {
            //Writes out error messages
            Response.Write("<br/><span style = 'color: red ; position: absolute; top: 360px; left: 90px;'>" + Msg + "</span>");           
        }
//ENDS DATA AND ERROR MESSAGES


    }//end Function: private void BtnSubmit_click...

}
4

4 に答える 4

2

MSDN から: https://msdn.microsoft.com/en-us/library/0yd65esw.aspx

例外がスローされると、共通言語ランタイム (CLR) は、この例外を処理する catch ステートメントを探します。現在実行中のメソッドにそのような catch ブロックが含まれていない場合、CLR は現在のメソッドを呼び出したメソッドを調べ、コール スタックを調べます。catch ブロックが見つからない場合、CLR は未処理の例外メッセージをユーザーに表示し、プログラムの実行を停止します。

try ブロックには、例外を引き起こす可能性のある保護されたコードが含まれています。ブロックは、例外がスローされるか、正常に完了するまで実行されます。

try... catch... ブロックは、論理的には条件のようなものと考えることができます。

たとえば、次のコードがあるとします。

string someString = "ABC";
DateTime someDate = DateTime.Parse(someString);

明らかに「ABC」は有効な DateTime ではありません。未処理の例外 (エラー) が原因で、アプリケーションがクラッシュします。

try... catch... ブロックで何かをラップするときは、基本的に次のように言っています。

try ブロックで例外が発生した場合は、try ブロック内のコードの実行を停止し、catch ブロック内のコードを実行して、何も起こらなかったように続行します。それ以外の場合は、catch ブロックのコードを無視してください。

これは、構造化例外処理と呼ばれます。コードの「危険な」領域が予想され、最悪のシナリオが発生した場合に備えて緊急コードを追加します。構造化された例外処理は、安全でないユーザー入力や、外部または信頼性の低いシステム (外部 Web サービスなど) を処理する場合に特に役立ちます。

例:

string someString = "ABC";
DateTime someDate;

try
{
    someDate = DateTime.Parse(someString);
}
catch
{
    // someString must not have been a valid DateTime!
    // Console.WriteLine($"Hey, {someString} is not a valid DateTime!"); 
    Console.WriteLine(String.Format("Hey, {0} is not a valid DateTime!", someString)); 
}

// Code continues executing because the exception was "caught"
于 2016-08-02T19:47:43.750 に答える
2

validateEntry = true;to 内に移動して、例外がスローtryされても設定しないようにします。DateTime.Parseあなたtry-catchのは大丈夫です。彼らは s のエラーDateTime.Parseキャッチします。

于 2016-08-02T19:52:31.587 に答える
2

TryParse を使用して有効な日付を確認できます

// valid Date
DateTime goodDate;
if (DateTime.TryParse("2000-02-02", out goodDate))
{
    Console.WriteLine(goodDate);
}

// not a date
DateTime badDate;
if (DateTime.TryParse("???", out badDate))
{
    Console.WriteLine(badDate);
}
else
{
    Console.WriteLine("Invalid");
}

地域に基づいた形式が必要な場合は、カルチャを含めることもできます。

string dateString;
      CultureInfo culture;
      DateTimeStyles styles;
      DateTime dateResult;    
// Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM";
      culture = CultureInfo.CreateSpecificCulture("en-US");
      styles = DateTimeStyles.None;
      if (DateTime.TryParse(dateString, culture, styles, out dateResult))
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, dateResult, dateResult.Kind);
      else
         Console.WriteLine("Unable to convert {0} to a date and time.", 
                           dateString);
于 2016-08-02T19:43:59.463 に答える
1

本当に正確にしたい場合:

        DateTime dateValue;

        var isDatePass = DateTime.TryParseExact("03/08/2002", "MM/dd/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);

常に事前検証を使用できることに注意してください。

于 2016-08-02T19:44:08.173 に答える