Reputation: 307
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++)
{
Integers.Add();
}
}
Give me a hint please
Upvotes: 0
Views: 4374
Reputation: 1
Declare your list globally as
List<int> listInt = new List<int>();
In the click event of your button, add following code
if(!string.IsNullOrEmpty(textBox1.Text))
listInt.Add(Convert.ToInt32(textBox1.Text));
This would only insert Int32 values. Any other input would give an exception.
Upvotes: 0
Reputation: 3576
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))
myNumbers.Add(int.Parse(str));
}
}
Upvotes: 3
Reputation: 1382
Unless you show your code It would be hard to suggest something just a hint
TextItem is by default a string so Might be Your List is an int Try:
var a =int.Parse(textbox1.Text);
myList.Add(a);
Would be helpful for you.
Upvotes: 0