ank*_*ung 5 .net c# textbox winforms
我是新手.Net Framework
,我想在我的Windows窗体应用程序中添加验证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; }
}
}
Run Code Online (Sandbox Code Playgroud)
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,
}
Run Code Online (Sandbox Code Playgroud)
构建您的解决方案。从 中选择新创建的控件Toolbox
。在窗体中拖动,然后更改ControlType
属性Property Window
。示例仅显示数字和文本,但您可以扩展电话、电子邮件等所有内容。
编辑
还可以在 enum 中使用默认标记,这将使其成为正常的Textbox
. 在这种情况下,不要忘记取消事件的链接。
希望能帮助到你。
归档时间: |
|
查看次数: |
302 次 |
最近记录: |