foreach (Control c in groupBox1.Controls)
{
if (c is TextBox)
{
if (((TextBox)c).Text == null || ((TextBox)c).Text.Length == 0 || ((TextBox)c).Text == " ")//判斷輸入的數值不能為空
{
MessageBox.Show("請輸入數值!");
return;
}
if (!Validate(((TextBox)c).Text.Trim(), @"^(-?\d+)(\.\d+)?$"))//判斷輸入的數值只能是數值
{
MessageBox.Show("只能輸入數值!");
return;
}
}
}
static public bool Validate(string str, string regexStr)
{
Regex regex = new Regex(regexStr);
Match match = regex.Match(str);
if (match.Success)
return true;
else
return false;
}
注意:!!需要引用using System.Text.RegularExpressions;