首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

怎么使textbox只能输入数字和小数点

2012-01-11 
如何使textbox只能输入数字和小数点比如要实现两个textbox,在里面输入数字,按下button时在另一个textbox中

如何使textbox只能输入数字和小数点
比如要实现两个textbox,在里面输入数字,按下button时在另一个textbox中显示两个数的和

添加控件之后的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();
  }

  private void button1_Click(object sender, EventArgs e)
  {
  //在此加入实现相加的代码
  }
   
  }
}

现在想要只让textbox只接受数字和小数点
google了一下,找到如下代码:
//KeyPress事件:当控件获得焦点,并且用户按下且释放键盘上的键后发生
  private void textBox1_KeyPress(object sender, KeyPressEventArgs e)//文本框只接受数字的输入和小数点
  {
  //IsNumber:指定字符串中位于指定位置的字符是否属于数字类别
  //IsPunctuation:指定字符串中位于指定位置的字符是否属于标点符号类别
  //IsControl:指定字符串中位于指定位置的字符是否属于控制字符类别
  if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
  {
  e.Handled = true; //获取或设置一个值,指示是否处理过System.Windows.Forms.Control.KeyPress事件
  }
  else if (Char.IsPunctuation(e.KeyChar))
  {
  if (e.KeyChar == '.')
  {
  if (((TextBox)sender).Text.LastIndexOf('.') != -1)
  {
  e.Handled = true;
  }
  }
  else
  {
  e.Handled = true;
  }
  }
  }

请问:1、Handled是什么属性?
2、我找到的这段代码应该加入什么位置?还要加什么控件不?

[解决办法]
1、Handled属性 --如果事件已完整地被处理,则为 true;否则为 false。 
2、那个代码加到TextBox1_TextChanged 下!
[解决办法]
不好意思,没看清要求.
当你要限制使textbox只能输入数字和小数点时,要这样写.
 private void button1_Click(object sender, EventArgs e)
{
///变量先初始化
int sum = 0;
int number1 = 0;
int number2 = 0;
///判断是否成功转换成数字
if (int.TryParse(textBox1.Text, out number1))//int number1 = int.Parse(textBox1.Text);
{
MessageBox.Show("success");
}
else
{
"Error,please try again.";
}
if (int.TryParse(textBox2.Text, out number2))//int number1 = int.Parse(textBox1.Text);
{
MessageBox.Show("success");
}
else
{
"Error,please try again.";
}//int number2 = int.Parse(textBox2.Text);
sum = number1 + number2;
textBox3.Text = sum.ToString(); 

}
快点给分啊,吼吼~~~~~~
[解决办法]
在TextBox的KeyPress事件中输入如下代码
private void textBoxYMaxScale_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 48 && e.KeyChar <= 57)
{
//为数字时

}
else if (e.KeyChar == 8)
{
//为删除键时

}
else if (e.KeyChar == 46)
{
//为点时

}
else
{


//其它所有字符
e.KeyChar = Convert.ToChar(20);
}
}
[解决办法]
private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
{

if ( e.KeyChar > (char)47 && e.KeyChar < (char)58 || e.KeyChar ==(char)8 ||e.KeyChar==(char)46)
{
e.Handled = false;
}
else
{
e.Handled = true;
MessageBox.Show("只能输入数字0-9和“.”如:(192.168.1.1)");
}

[解决办法]
for (int i = 0; i < textBox1.Text.Length; i++)
{
string f = textBox1.Text.Substring(i, 1).ToString().Trim();
if (f != "1" && f != "2" && f != "3" && f != "4" && f != "5" && f != "6" && f != "7" && f != "8" && f != "9" && f != "0" && f != ".")
{
MessageBox.Show("请输入数字类型!");
textBox1.Text = "";
}
}

热点排行