我想從文本文件中使用逗號作爲分隔符組合框填充一切工作正常,但現在當我調試我得到「索引超出範圍異常未處理」警告。我想我需要一雙新鮮的眼睛來看看我出錯的地方,我評論的那一行得到錯誤// Fname = fields [1];陣列幫助索引超出範圍異常未處理
private void xViewFacultyMenuItem_Click(object sender, EventArgs e)
{
const string fileStaff = "source\\Staff.txt";
const char DELIM = ',';
string Lname, Fname, Depart, Stat, Sex, Salary, cDept, cStat, cSex;
double Gtotal;
string recordIn;
string[] fields;
cDept = this.xDeptComboBox.SelectedItem.ToString();
cStat = this.xStatusComboBox.SelectedItem.ToString();
cSex = this.xSexComboBox.SelectedItem.ToString();
FileStream inFile = new FileStream(fileStaff, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
recordIn = reader.ReadLine();
while (recordIn != null)
{
fields = recordIn.Split(DELIM);
Lname = fields[0];
Fname = fields[1]; // this is where the error appears
Depart = fields[2];
Stat = fields[3];
Sex = fields[4];
Salary = fields[5];
Fname = fields[1].TrimStart(null);
Depart = fields[2].TrimStart(null);
Stat = fields[3].TrimStart(null);
Sex = fields[4].TrimStart(null);
Salary = fields[5].TrimStart(null);
Gtotal = double.Parse(Salary);
if (Depart == cDept && cStat == Stat && cSex == Sex)
{
this.xEmployeeListBox.Items.Add(recordIn);
}
recordIn = reader.ReadLine();
}
Source file --
Anderson, Kristen, Accounting, Assistant, Female, 43155
Ball, Robin, Accounting, Instructor, Female, 42723
Chin, Roger, Accounting, Full, Male,59281
Coats, William, Accounting, Assistant, Male, 45371
Doepke, Cheryl, Accounting, Full, Female, 52105
Downs, Clifton, Accounting, Associate, Male, 46887
Garafano, Karen, Finance, Associate, Female, 49000
Hill, Trevor, Management, Instructor, Male, 38590
Jackson, Carole, Accounting, Instructor, Female, 38781
Jacobson, Andrew, Management, Full, Male, 56281
Lewis, Karl, Management, Associate, Male, 48387
Mack, Kevin, Management, Assistant, Male, 45000
McKaye, Susan, Management, Instructor, Female, 43979
Nelsen, Beth, Finance, Full, Female, 52339
Nelson, Dale, Accounting, Full, Male, 54578
Palermo, Sheryl, Accounting, Associate, Female, 45617
Rais, Mary, Finance, Instructor, Female, 27000
Scheib, Earl, Management, Instructor, Male, 37389
Smith, Tom, Finance, Full, Male, 57167
Smythe, Janice, Management, Associate, Female, 46887
True, David, Accounting, Full, Male, 53181
Young, Jeff, Management, Assistant, Male, 43513
這麼長的代碼。至少給一些callstack – brickner 2010-06-07 16:19:22
你可以在調試器中運行它,看看當你試圖訪問「fields [1]」時有什麼「字段」? – bentsai 2010-06-07 16:19:57
在分割後插入'Debug.Assert(fields.Length == 6)'開始調試 – tanascius 2010-06-07 16:21:03