1

如何为. _Property _ UserControl考虑以下代码:

 public class Date

{
    private int month = 7;  // Backing store 

    public int Month
    {
        get
        {
            return month;
        }
        set
        {
            if ((value > 0) && (value < 13))
            {
                month = value;
            }
        }
    }
}

它将检查该Month值是否介于 1 和 12 之间,但我也希望显示无效输入消息,以防它无效。有任何想法吗 ?

4

1 回答 1

2

如果值不在 1 到 12 之间,您可以抛出例如 anInvalidOperationException并在主线程中处理它。

public int Month
{
    get
    {
        return month;
    }
    set
    {
        if ((value > 0) && (value < 13))
        {
            month = value;
        }
        else throw new InvalidOperationException("Invalid month");
    }
}

然后像...

private void textBox1_Validating(object sender, CancelEventArgs e)
{
   try
   {
      date.Month = Convert.ToInt32(textbox1.Text);
   }
   catch(InvalidOperationException ex)
   {
      e.Cancel = true;
      textBox1.Select(0, textBox1.Text.Length);

      // some message about invalid value
   }
}

textBox1_Validating文本框的验证事件处理程序在哪里。

于 2013-08-21T06:40:01.793 回答