开发步骤
(1)新建一个Windows应用程序,将其命名为“自制数值文本框组件”,默认窗体为Form1。
(2)在当前项目中添加一个用户控件,将其命名为NumberBox。将用户控件的UserControl类改为TextBox类。
(3)主要程序代码。
限制文本框的输入范围主要是在文本框的KeyPress事件中进行,如果在自定义控件中触发该事件,则对其进行重载。实现代码如下:
public NumberBox()
{
InitializeComponent();
//对KeyPress事件进行重载
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.numberBox1_KeyPress);
//对Leave事件进行重载
this.Leave += new System.EventHandler(this.numberBox1_Leave);
}
numberBox1控件的KeyPress事件主要用于限制文本框中输入的字符只能是数值型。实现代码如下:
/// <summary>
/// 执行自定义控件的KeyPress事件
/// </summary>
protected virtual void numberBox1_KeyPress(object sender, KeyPressEventArgs e)
{
Estimate_Key(e, ((TextBox)sender).Text, Convert.ToInt32(this.DataStyle));
}
自定义方法Estimate_Key主要是判断文本框中输入的字符是整型还是单精度型,如果是单精度型,可以在文本框中输入数字、“.”或“-”;如果是整型,只能在文本框中输入数字和“-”。实现代码如下:
/// <summary>
/// 根据属性设置文本框中的内容
/// </summary>
public void SetTextBox()
{
bool tem_BoolInt = true; //定义一个变量,判断是否为数值型
if (this.Multiline == true) //如果允许输入多行
return; //退出当前操作
if (this.Text.Length == 0) //如果Text属性为空
return; //退出当前操作
if (this.Text.Trim() == "-")
{
this.Text = "";
return; //退出当前操作
}
else
{
char tem_char = '0';
for (int i = 0; i < this.Text.Length - 1; i++) //循环遍历文本框中的数值
{
tem_char = Convert.ToChar(this.Text.Substring(i, 1)); //获取单个字符
if ((tem_char > '9' || tem_char < '0')) //如果字符不是数字
{
if (!(tem_char == '.' || tem_char == '-')) //如果字符不是'.'和'-'
{
//当前文本不能转换成数值型数据
MessageBox.Show("无法将字符串转换成整数或小数");
ifInt = false;
this.DataStyle = StyleSort.Null;
return;
}
}
}
if (tem_BoolInt) //如果是数值型
{
Decimal tem_value = Convert.ToDecimal(this.Text); //获取当前的值
switch (Convert.ToInt32(this.DataStyle)) //根据数据类型来进行操作
{
case 1: //整型
case 2: //小数
{
if (Math.Floor(tem_value) == tem_value) //如果输入的是整型
break; //不进行操作
switch (Convert.ToInt32(this.ReservedStyle)) //判断小数的保留类型
{
case 0: //保留最小整数
{
tem_value = Math.Floor(tem_value);
break;
}
case 1: //对小数进行四舍五入
{
if (Convert.ToInt32(this.DataStyle) == 1)//对第一位小进行四舍五入
{
tem_value = Math.Round(tem_value, 1);
}
else//对指定位数的小数进行四舍五入
{
tem_value = Math.Round(tem_value, this.ReservedDigit);
}
break;
}
case 2: //保留最大整数
{
tem_value = Convert.ToDecimal(this.Text);//将文本框转换成双精度
tem_value = Math.Ceiling(tem_value);//取最小整数
break;
}
case 3: //保留指定的小数位数
{
string var_str = this.Text;
if (Convert.ToInt32(this.DataStyle) == 2)
{
tem_value = Convert.ToDecimal(var_str.Substring(0, var_str.IndexOf('.') + ReservedDigit + 1));
}
break;
}
}
break;
}
}
this.Text = tem_value.ToString(); //显示保留后的数据
}
}
}