将文本框值添加到列表
本文关键字:列表 添加 文本 | 更新日期: 2023-09-27 18:36:52
List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers[0] = int.Parse(textBoxNum1.Text);
textBoxNum1 的值为 5
此代码给出错误
Index was out of range. Must be non-negative and less than the size of the collection.
为什么?
这是因为您的列表当前为空,因此您无法将第一个索引设置为某些内容(因为它不存在)。 如果您这样做:
List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers.Add(int.Parse("5"));
MyLottoNumbers[0] = int.Parse("7");
它有效,因为该索引已设置。
如果要在前面插入,请走以下路线:
List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers.Insert(0, int.Parse(textBoxNum1.Text));
您需要将文本框的值.Add()
到List
。 喜欢这个:
List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers.Add(int.Parse(textBoxNum1.Text);
当您new
一个List
时,它的大小将设置为 0,直到您向其.Add()
项目。
创建一个新列表
new List<int>();
创建一个大小为 0 的列表 (http://msdn.microsoft.com/en-us/library/4kf43ys3(v=vs.110).aspx)。
使用 [0],您正在尝试获取位置 0 的元素。大小为零的列表没有 0 索引 -> 索引超出范围
有关如何使用 List 的示例,请参阅 http://www.dotnetperls.com/list。
在这种情况下,它将是:
MyLottoNumbers.Add(int.Parse(textBoxNum1.Text));
"添加"会在列表末尾添加值。
是的,但是如果我必须将值添加到特定列表值中,该怎么办 说明?
您似乎想在特定索引处添加值。如果在设计时知道列表的大小,则应考虑使用数组而不是列表。
请尝试使用正则表达式和 linq 创建和解析列表。
请注意,它假设用户正在放置空格进行拆分,例如"5 12 15",如下所示:
if (string.IsNullOrWhiteSpace(textBoxNum1.Text) == false)
{
MyLottoNumbers = Regex.Matches(textBoxNum1.Text, @"([^'s]+)'s*")
.OfType<Match>()
.Select(mt => int.Parse(mt.Groups[0].Value))
.ToList();
}
else
{
MyLottoNumbers = new List<int>(); // Create empty list as to not throw an exception.
}
如果您阅读异常消息,它会说:
指数超出范围。必须为非负数且小于集合的大小
发生这种情况是因为创建时列表的元素长度为0(检查MyLottoNumbers.Count)。这在构造函数的摘要中有所说明:
公共列表() System.Collections.Generic.List 的成员
摘要:初始化 System.Collections.Generic.List 类为空,具有 默认初始容量。
你正在尝试使用索引器:
public T this[int index] { set; get; } System.Collections.Generic.List 的成员
摘要:获取或设置指定索引处的元素。
将元素设置为位置 0。但是,您会收到一个异常,因为实际上还没有位于位置 0 的元素(因为列表为空)。
执行MyLottoNumbers.Add
时,列表大小会增加。
您真正需要做的是:
MyLottoNumbers.Add(int.Parse(textBoxNum1.Text);
铌:这是列表和数组之间的区别之一:列表在创建时为空,而数组则不是。因此,您可以使用数组重写示例:
int[] MyLottoNumbers = new int[25];
MyLottoNumbers[0] = int.Parse("5");