-7

についてお尋ねしSchoolYearます。

この例のように

2013-2014 (開始年-終了年)

ユーザーが実際に学年を入力しているかどうかを検証する方法 (例2013-2014)

これは私がこれまでに試したことです。

 private void TextBox_Validating(object sender, CancelEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(studentLastSchoolAttendedSchoolYearTextBox.Text))
            {
                int fromYear = 0;
                int toYear = 0;
                string[] years = Regex.Split(studentLastSchoolAttendedSchoolYearTextBox.Text, @"-");

                fromYear = int.Parse(years.FirstOrDefault().ToString());
                if (fromYear.ToString().Length == 4)
                {
                    if (years.Count() > 1)
                    {
                        if (!string.IsNullOrWhiteSpace(years.LastOrDefault()))
                        {
                            toYear = int.Parse(years.LastOrDefault().ToString());
                            if (fromYear >= toYear)
                            {
                                e.Cancel = true;
                                MessageBox.Show("The 'From Year' must be lesser than to 'To Year'.\n\nJust leave as a empty to avoid validating.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }
                        else
                        {
                            e.Cancel = true;
                            MessageBox.Show("Please enter a valid School range Year format.\nEx.: 2010-2011\n\nJust leave as empty to avoid validating.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                    else
                    {
                        studentLastSchoolAttendedSchoolYearTextBox.Text = fromYear.ToString() + "-" + Convert.ToInt32(fromYear + 1).ToString();
                    }
                }
                else
                {
                    e.Cancel = true;
                    MessageBox.Show("Please enter a valid School range Year format.\nEx.: 2010-2011\n\nJust leave as empty to avoid validating.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
4

2 に答える 2

2

2013-2014それが有効な形式であると仮定すると、これは機能する関数になる可能性があります。

public static bool IsSchoolYearFormat(string format, int minYear, int maxYear)
{
    string[] parts = format.Trim().Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
    if (parts.Length == 2)
    {
        int fromYear; int toYear;
        if (int.TryParse(parts[0], out fromYear) && int.TryParse(parts[1], out toYear))
        {
            if (fromYear >= minYear && toYear <= maxYear && fromYear + 1 == toYear)
                return true;
        }
    }
    return false;
}
于 2013-02-18T21:28:15.220 に答える