将字符串转换为整数

3

我需要帮助我的代码。我想在文本框中只写数字/整数,并希望在列表框中显示。

下面的代码是否正确?这似乎会导致错误。


我需要帮助翻译其他内容吗?
    int yourInteger;
    string newItem;

    newItem = textBox1.Text.Trim();

    if (newItem == Convert.ToInt32(textBox1.Text))
    {
        listBox1.Items.Add(newItem);
    }

==== 更新:

现在我的代码看起来是这样的。我的问题是,listBox能够处理"long"数据类型吗?因为当我输入数字20,000,000时,我只得到了一个小时glass,持续了20分钟。但是当我尝试用控制台运行时,我得到了答案。所以我不确定哪种元素可以处理"long"数据类型。

    string newItem;
    newItem = textBox1.Text.Trim();

    Int64 num = 0;
    if(Int64.TryParse(textBox1.Text, out num))
    {
        for (long i = 2; i <= num; i++)
        {
            //Controls if i is prime or not
            if ((i % 2 != 0) || (i == 2))
            {
                listBox1.Items.Add(i.ToString());
            }

        }
    }


    private void btnClear_Click(object sender, EventArgs e)
    {
        listBox1.Items.Clear();
    }
7个回答

14
int result = int.Parse(textBox1.Text.Trim());

如果你想检查有效性:

int result;
if (int.TryParse(textBox1.Text.Trim(), out result)) // it's valid integer...
   // int is stored in `result` variable.
else
   // not a valid integer

嗨Mehrdad,我不确定如何在我的代码中实现这个。也许你可以帮我一下。谢谢。 - tintincutes
这不是long类型的问题。你正在执行非常耗费时间和内存的操作。向控制台写入不需要更新具有大量元素的GUI对象。基本上,你正在在一个没有任何实际用途(谁能滚动查看如此长的列表?)且消耗大量资源的列表框中显示数百万个元素。 - Mehrdad Afshari
嗨Mehrdad,这只是一个用于学习的测试程序。谢谢你的建议。 - tintincutes

3
使用以下内容:
    int yourInteger;
    string newItem;

    newItem = textBox1.Text.Trim();
    Int32 num = 0;
    if ( Int32.TryParse(textBox1.Text, out num))
    {
        listBox1.Items.Add(newItem);
    }
    else
    {
        customValidator.IsValid = false;
        customValidator.Text = "You have not specified a correct number";
    }

这假定您有一个自定义验证器。

这个代码是可行的,但问题在于:如果我输入字符,它就不会给我任何消息或错误。是否也可能在这里集成"try and catch"? - tintincutes
这是一个方法吗?它会是什么样子? - tintincutes

1
使用 int.TryParse() 检查字符串是否包含整数值。

0

你可以做:

Convert.ToInt32(input);

如果您想查看更长的使用此功能的函数,请参阅: http://msdn.microsoft.com/en-us/library/bb397679.aspx

基本上,它会检查字符串是否为空,然后调用int.Parse。这也适用于WindowsCE,因为它没有int.TryParse。


0
具体来说,你的代码无法编译是因为你正在将一个字符串(newItem)与 Convert.ToInt32 的结果进行比较,而 Convert.ToInt32 是一个整数,它不允许你这样做。此外,如果传入的字符串不是数字,Convert.ToInt32 将引发异常。
你可以尝试使用 int.TryParse,或者编写一个简单的正则表达式来验证输入:
int i;
bool isInteger = int.TryParse(textBox1.Text,out i);

或者

bool isInteger = System.Text.RegularExpressions.Regex.IsMatch("^\d+$", textBox1.Text);

0

textBox1.Text 可能不包含一个整数的有效字符串表示(或者只是一个空字符串)。为了解决这个问题,可以使用 Int32.TryParse()


-1
你是在检查一个空字符串吗?
int yourInteger;
string newItem;
newItem = textBox1.Text.Trim();

if(newItem != string.Empty)
{
   if ( newItem == Convert.ToInt32(textBox1.Text))
   {
      listBox1.Items.Add(newItem);
   }
}

1
谢谢Pat,我尝试了这个,但是出现了错误:"无法将'=='运算符应用于类型为'string'和'int'的操作数"。 - tintincutes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接