繁体   English   中英

转换为整数时输入字符串格式不正确

[英]Input string was not in a correct format when converting to integer

排队:

int d = Convert .ToInt32 ( TxtAmount.Text); 

有一个错误

输入的字符串格式不正确

我想转换TxtAmount.Text内部的TxtAmount.Text 如果它是一个十进制的负数或不带-整数,则将其再次转换为字符串,因为ConvertNumbersToArabicAlphabet参数为字符串。

int d = Convert .ToInt32 ( TxtAmount.Text);
ConvertNumbersToArabicAlphabet a = new ConvertNumbersToArabicAlphabet(d.ToString());
Label2.Text = a.GetNumberAr();

我先检查输入是否为数字,然后使用Math.Abs进行转换以确保结果始终为正数:

int result = 0;

// Does text contain numbers only (and maybe a leading "-")?
if (Regex.IsMatch(TxtAmount.Text, @"^-?[0-9]+$"))
{
    // Try to parse an int from it. If successful, convert it to
    // a positive number in any case (= ignore the leading "-")
    if (Int32.TryParse(TxtAmount.Text, out result))
        result = Math.Abs(result);
}

// In all other cases, the result is 0
return result;

这是因为Youse文本框为空。 检查天气,您的文本框是否具有值

if(!String.IsNullOrWhiteSpace(TxtAmount.Text))
{
   int d = Convert .ToInt32 ( TxtAmount.Text); 
}
int d = Convert .ToInt ( TxtAmount.Text); 

如果文本框内有整数值,则可以使用它。 如果文本区域仅包含一个字符,那么它将不再起作用。

尝试只将要转换为数据类型相同的Integer放入文本框

例如,如果您想添加一个双数,则可以使用。

Double num = Convert .ToDouble ( TxtAmount.Text); 

如果您的文本框为空,则可以确保您已通过验证或检查是否相同:

if(TxtAmount.Text==""||TxtAmount.Text=string.Empty)
{
    TxtAmount.Text=0;
}
else
{
  int d = Convert .ToInt ( TxtAmount.Text); 
}

如果您只想忽略负号,则可以执行如下字符串操作:

string value = TxtAmount.Text;
if (value.StartsWith("-"))
{
    value = value.Substring(1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM