【发布时间】:2019-06-28 08:38:44
【问题描述】:
我有两个字符串列表:
currentRow = 包含行应该包含的信息
currentCol = 包含来自 currentRow 的数据应该进入的列的名称。
每个 List 包含 25(0-24) 个项目,并且按照与它应该写入的 dataRow 相同的方式排序。
我在这里填写列表,来自表单上的标签和文本框:
List<string> currentRow = new List<string>();
List<string> currentCol = new List<string>();
foreach (var c in form11.Controls)
{
if (c.GetType() == typeof(TextBox))
{
var str = c.ToString();
var str1 = str.Substring(35);
currentRow.Add(str1);
}
if (c.GetType() == typeof(Label))
{
var str = c.ToString();
var str1 = str.Substring(34);
currentCol.Add(str1);
}
}
然后我从 currentRow 中的第 3 项中选择需要更新的数据表中的行,这是一个唯一标识符。
var updateRow = arraysDt.Select("SERIAL =" + "'" + currentRow.ElementAtOrDefault(2) + "'");
现在我尝试从此处列表中的项目更新该行:
for (int i = 0; i < currentRow.Count; i++)
{
//MessageBox.Show(currentCol.ElementAtOrDefault(i).ToString() + " " + currentRow.ElementAtOrDefault(i).ToString());
updateRow[0][currentCol.ElementAtOrDefault(i)] = currentRow.ElementAtOrDefault(i);
}
只要它进入 for 循环,我就会抛出“索引超出数组范围”错误。
正如我所说,currentCol 包含列名,而 currentRow 是值。 所以当它到达这里时,我希望它找到列名,然后用值更新它。
updateRow[0][currentCol.ElementAtOrDefault(i)] = currentRow.ElementAtOrDefault(i);
我做错了什么?
【问题讨论】:
-
i 是行数还是列数? 1) i
-
@jdweng "i" 是列表中有多少项目的计数。所以 for 循环应该运行与列表中的项目相同的次数。这是25次。因此,在它说“currentCol.ElementAtOrDefault(i)”的地方,“i”将是列名,而 currentRow.ElementAtOrDefault(i) 将是它应该设置的值。
标签: c# for-loop indexoutofboundsexception