Matviei Skufin Matviei Skufin - 1 year ago 81
C# Question

How to add numbers to ArrayList or List<int> from textbox

I want to add numbers to ArrayList or List from textBox.
I think that when user writes numbers to textBox , textBoxe's text converts to string and splits on ArrayList elements. But I have no idea how to do it. I've tried very long time and always had an InvalidCastException.

ArrayList Integers = new ArrayList();
private void button1_Click_1(object sender, EventArgs e)
for (int i = 0; i < textBox1.Text.Split(new char[] { ' ' }).Length; i++)

Give me a hint please

Answer Source

Declare an Integer List inside your Form class and use TryParse to convert the TextBox string to integer and manage possible exceptions when you add values

    List<int> myNumbers = new List<int>();

    private void button1_Click(object sender, EventArgs e)
        int i;
        foreach (string str in textBox1.Text.Split(' '))
            if (int.TryParse(str, out i))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download