簡體   English   中英

如何將文本框值轉換為整數

[英]How to convert textbox value to integer

我的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);

如果文本框沒有值,請輸入0並轉換為整數,否則將文本框的值轉換為整數。

我收到了inCyan的以下錯誤,其中文本框為空:

Input string was not in a correct format.

我怎樣才能實現我想要的目標?

而不是Convert.ToInt32 ,使用Int32.TryParse 這會為您提供有關它是否為有效整數的反饋。 例如

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.
}

作為后續, String.IsNullOrWhitespace可以在提供值時輕松解密,但是(取決於您的.NET版本)可能不可用(並且您可能只有String.IsNullOrEmpty

如果需要,填充物可以是以下方面:

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到value。

如何將其應用於您的特定問題。

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

etc.....

你可以使用tryparse。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM