字符串转换为整数 [英] Convert string to integer

查看:114
本文介绍了字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

下面是为了我的code?这似乎给出错误。

  INT yourInteger;
    字符串的newitem;

    的newitem = textBox1.Text.Trim();

    如果(的newitem == Convert.ToInt32(textBox1.Text))
    {
        listBox1.Items.Add(的newitem);
    }
 

==== 更新:

这是我的code貌似现在。我的问题是,列表框的处理数据类型长?因为当我输入的号码20000000我刚刚得到一个沙漏20分钟。但是,当我尝试这一个与控制台,我得到了答案。所以,我不知道什么样的元素可以处理的数据类型长。

 字符串的newitem;
    的newitem = textBox1.Text.Trim();

    INT64 NUM = 0;
    如果(Int64.TryParse(textBox1.Text,出NUM))
    {
        为(长I = 2; I< = NUM​​;我++)
        {
            //控制,如果我是素数或不
            如果((ⅰ%2!= 0)||(ⅰ== 2))
            {
                listBox1.Items.Add(i.ToString());
            }

        }
    }


    私人无效btnClear_Click(对象发件人,EventArgs的)
    {
        listBox1.Items.Clear();
    }
 

解决方案

使用这样的:

  INT yourInteger;
    字符串的newitem;

    的newitem = textBox1.Text.Trim();
    INT32 NUM = 0;
    如果(Int32.TryParse(textBox1.Text,出NUM))
    {
        listBox1.Items.Add(的newitem);
    }
    其他
    {
        customValidator.IsValid = FALSE;
        customValidator.Text =您还没有指定一个正确的号码;
    }
 

这里假设你有一个的CustomValidator。

I need help with my code. I would like to write only numbers/integers in my textbox and would like to display that in my listbox.

Is my code below in order? This seems to give an error.

    int yourInteger;
    string newItem;

    newItem = textBox1.Text.Trim();

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

==== Update:

This is how my code looks like now. My question is, can listBox handle the data type "long"? Because when I entered the number 20,000,000 I just got an hour glass for 20 minutes. But when I tried this one with the console, I got the answer. So I'm not sure what kind of element can handle data type "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();
    }

解决方案

Use this:

    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";
    }

This assumes you have a customValidator.

这篇关于字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆