gpt4 book ai didi

c# - 错误 : (using List class) Index was outside the bounds of array

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:41 24 4
gpt4 key购买 nike

我正在做一个项目,我是 c# 编程的初学者,但不知何故,我遇到了一个我无法解决的问题。它是如何发生的:在执行代码时,应用程序成功启动但出现异常显示“索引超出数组范围”。之后,我能够单击列表框中的项目,它会在文本框中显示第二个对象。所以......它似乎有效(点击列表框的项目)但我无法弄清楚为什么它会抛出关于数组的异常。下面是我的当前代码。

**更新:我真诚地道歉。我上传了错误的代码。应该是这段代码:

代码:

struct studentInfo
{
public string studentID;
public string major;
}

public partial class Form1 : Form
{
private List<studentInfo> studentList = new List<studentInfo>();

public Form1()
{
InitializeComponent();
}


private void ReadInputFile()
{
try
{
StreamReader inputFile;
string line = "";

studentInfo student = new studentInfo();

char[] delimiter = { ',' };

inputFile = File.OpenText("Student Info.txt");

while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();

string[] token = line.Split(delimiter);

student.studentID = token[0];
student.major = token[1];

studentList.Add(student);

}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void DisplaystudentID()
{
foreach (studentInfo student in studentList)
{
studentInfoListBox.Items.Add(student.studentID);
}
}

private void DisplayNames()
{

}
private void button1_Click(object sender, EventArgs e)
{
ReadInputFile();

DisplaystudentID();
}

private void studentInfoListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = studentInfoListBox.SelectedIndex;

majorTextBox.Text = studentList[index].major;


}

private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
}

最佳答案

我的猜测是 SelectedIndexChanged 在开始时运行(在您选择任何内容之前)并且此时 nameListBox.SelectedIndex 将为 -1 并且您无法在列表中获得“负 1 位置的项目”。我会确保所选索引有效

https://msdn.microsoft.com/fr-fr/library/system.windows.forms.listbox.selectedindex(v=vs.110).aspx“当前所选项目的从零开始的索引。如果未选择任何项目,则返回负一 (-1) 值。”

我会这样修改代码:

private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = nameListBox.SelectedIndex;
if(index !=-1)
{
phoneLabel.Text = phoneList[index].phone;
}
// else do nothing, the selected item didn't really change, it's just called for the first time, think of it as the control saying "hey i just got created and i'm notifying you that the selected item is now nothing"
}

关于c# - 错误 : (using List class) Index was outside the bounds of array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37851354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com