5

我是新手.Net Framework,我想在Visual Studio 2010 IDE. 我已经搜索了不同的方法来做到这一点,但我不确定在哪里可以在我的表单中添加该代码?示例之一是下面的代码。

我是否将此代码添加到表单加载方法或提交按钮或其他地方?

using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }

        [Required(ErrorMessage = "Title is required")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Date is required")]
        public DateTime ReleaseDate { get; set; }

        [Required(ErrorMessage = "Genre must be specified")]
        public string Genre { get; set; }

        [Required(ErrorMessage = "Price Required")]
        [Range(1, 100, ErrorMessage = "Price must be between $1 and $100")]
        public decimal Price { get; set; }

        [StringLength(5)]
        public string Rating { get; set; }
    }

    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}
4

2 回答 2

1

TextBox尝试使用(如数字、文本)等公共属性创建自定义ControlType,然后为每种类型编写实现。下面给出的代码示例。

class CustomTextbox : TextBox
{
    private ControlType _controlType;

    public CustomTextbox()
    {
        Controltype = ControlType.Number;
    }

    public ControlType Controltype
    {
        get { return _controlType; }
        set
        {
            switch (value)
            {
                case ControlType.Number:
                    KeyPress += textboxNumberic_KeyPress;
                    MaxLength = 13;
                    break;

                case ControlType.Text:
                    KeyPress += TextboxTextKeyPress;
                    MaxLength = 100;
                    break;
            }
            _controlType = value;
        }
    }

    private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
    {
        const char delete = (char)8;
        const char plus = (char)43;
        e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != delete && e.KeyChar != plus;
    }

    private void TextboxTextKeyPress(object sender, KeyPressEventArgs e)
    {
        const char delete = (char)8;
        const char plus = (char)43;
        e.Handled = Char.IsDigit(e.KeyChar);
    }

}

public enum ControlType
{
    Number,
    Text,
}

构建您的解决方案。从 中选择新创建的控件Toolbox。拖入表单,然后ControlType从 更改属性Property Window。示例仅显示数字和文本,但您可以扩展电话、电子邮件和所有内容。

编辑

也可以在 enum 中使用默认标签,使其成为正常的Textbox. 在这种情况下,不要忘记取消链接事件。

希望能帮助到你。

于 2013-02-25T11:06:29.207 回答
0

我认为你应该使用IDataErrorInfo界面(见这里

是有关如何实现它的示例

它是这样的:

public class Movie : IDataErrorInfo
{
   public int ID { get; set; }

  //other properties removed for clearyfication

       private string _lastError = "";

        public string Error
        {
            get { return _lastError; }
        }

        public string this[string columnName]
        {
            get 
            {
               if(columnName == "ID" && ID < 0)
                 _lastError = "Id must be bigger that zero";
            }
        }

}
于 2013-02-25T11:38:33.427 回答