Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add textbox value to list

Tags:

c#

list

List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers[0] = int.Parse(textBoxNum1.Text);

textBoxNum1 has a value of 5

This code gives the error

Index was out of range. Must be non-negative and less than the size of the collection.

Why ?

like image 653
user1438082 Avatar asked Jan 22 '26 03:01

user1438082


1 Answers

It's because your list is currently empty, so you can't set the first index to something (because it doesn't exist). If you did this:

List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers.Add(int.Parse("5"));
MyLottoNumbers[0] = int.Parse("7");

it works, because that index has been set.

If you want to insert at the front, take this route:

List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers.Insert(0, int.Parse(textBoxNum1.Text));
like image 151
Jonesopolis Avatar answered Jan 23 '26 19:01

Jonesopolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!