C#驗證輸入的是否數位幾種方法

static bool IsNumeric(string str)
{
if (str==null || str.Length==0)
return false;
foreach(char c in str)
{
if (!Char.IsNumber(c))
{
return false;
}
}
return true;
}

方法二:

private bool IsNumeric(string s)

private bool IsNumeric(string s)

{

char ch0 = '0';

char ch9 = '9';

for(int i=0; i < s.Length; i++)

{

if ((s[i] < ch0 || s[i] > ch9))

{

this.lblwarning.Text="此處應輸入整數且非負！";

return false;

}

}

return true;

}

方法三:

static bool IsNumeric (string str)
{
System.Text.RegularExpressions.Regex reg1
= new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*\$");
return reg1.IsMatch(str);
}

方法四：（可擴充）

public static bool IsConvert(string Expression,Type DataType)

{

switch(DataType.Name)

{

case "Double":

try

{

Double.Parse(Expression);

return true;

}

catch

{

return false;

}

case "DateTime":

try

{

DateTime.Parse(Expression);

return true;

}

catch

{

return false;

}

default:

return true;

}

}

C#驗證輸入的是否數位方法

static bool IsNumeric(string str)
{
if (str==null || str.Length==0)
return false;
foreach(char c in str)
{
if (!Char.IsNumber(c))
{
return false;
}
}
return true;
}

static bool IsNumeric(string str)
{
System.Text.RegularExpressions.Regex reg1
= new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*\$");
return reg1.IsMatch(str);
}

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD