C# 如何将文本框值转换为整数

C# 如何将文本框值转换为整数,c#,winforms,C#,Winforms,我的C#windows窗体应用程序中有一些文本框。我想做以下工作: inRed = Convert.ToInt32(tbRed.Text.ToString().Length < 0 ? tbRed.Text = "0" : tbRed.Text); inGreen = Convert.ToInt32(tbGreen.Text.ToString().Length < 0 ? tbGreen.Text = "0" : tbGreen.Text); inBlue = Convert.ToI

我的C#windows窗体应用程序中有一些文本框。我想做以下工作:

inRed = Convert.ToInt32(tbRed.Text.ToString().Length < 0 ? tbRed.Text = "0" : tbRed.Text);
inGreen = Convert.ToInt32(tbGreen.Text.ToString().Length < 0 ? tbGreen.Text = "0" : tbGreen.Text);
inBlue = Convert.ToInt32(tbBlue.Text.ToString().Length < 0 ? tbBlue.Text = "0" : tbBlue.Text);

inCyan = Convert.ToInt32(tbCyan.Text.ToString().Length < 0 ? tbCyan.Text = "0" : tbCyan.Text);
inMagenta = Convert.ToInt32(tbMagenta.Text.ToString().Length < 0 ? tbMagenta.Text = "0" : tbMagenta.Text);
我如何才能实现我所追求的目标?

你可以使用tryparse

int inRed;  //default value will be 0 , if the string is not in a  valid form
Int32.TryParse(tbRed.Text.ToString(), out inRed);

不要使用
Convert.ToInt32
。这将为您提供有关它是否为有效整数的反馈。e、 g

String textboxValue = "1";
Int32 i;
if (!String.IsNullOrWhitespace(textboxValue) && // Not empty
    Int32.TryParse(textboxValue, out i)) { // Valid integer
  // The textbox had a valid integer. i=1
} else {
  // The texbox had a bogus value. i=default(Int32)=0
  // You can also specify a different fallback value here.
}
作为后续操作,如果提供了值,则可以很容易地进行解密,但是(取决于您的.NET版本)可能不可用(并且您可能只有一个值)

如果需要,polyfill可以是以下几行:

Boolean SringIsNullOrWhitespace(String input)
{
    return !String.IsNullOrEmpty(input) && input.Trim().Length > 0;
}
此外,如果您发现自己经常尝试执行此解析,则可以将其重构为帮助器类:

public static class ConvertUtil
{
    public Int32 ToInt32(this String value)
    {
        return ToInt32(value, default(Int32));
    }
    public Int32 ToInt32(this String value, Int32 defaultValue)
    {
#if NET4
        if (!String.IsNullOrWhiteSpace(value))
#else
        if (!String.IsNullOrEmpty(value) && value.Trim().Length > 0)
#endif
        {
            Int32 i;
            if (Int32.TryParse(value, out i))
            {
                return i;
            }
        }
        return defaultValue;
    }
}

// explicit
inRed = ConvertUtil.ToInt32(tbRed.Text, 0/* defaultValue*/);
// As extension
inRed = tbRed.Text.ToInt32(0/* defaultValue*/);

你可以这样做

// Initialise variable with 0
int value;

// Try parse it, if it's successful and able to parse then value is set to         the int equivalent of your text input
int.TryParse(inputVariable, out value);

return value
这是一种处理问题的简单方法-注意,如果解析失败,那么它将返回0到值

如何将其应用于您的特定问题

int inMagenta;
int.TryParse(tbMagenta, out inMagenta);

etc.....

尝试使用
Length为什么要将ToString添加到字符串属性?@DavidG Wow…缺少
=
。谢谢。对于输入数值,您可以使用该控件。它完全消除了解析。@juharr实际上我不会使用此方法,因为如果输入非数值,它仍然会生成异常。只需添加一些对于OP的信息,
TryParse
将在转换失败时返回值
0
。否,
TryParse
返回布尔值。正确的检查方法是
if(TryParse(…)
@DionV。是的,它以布尔值给出Int输出in-out参数和转换状态。您需要使用“out”for out参数
int inMagenta;
int.TryParse(tbMagenta, out inMagenta);

etc.....