Convert string to integer

.net, c#, integer, string

Solution

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.

Problem

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(); } ```

Original source