2

I am trying to populate combo boxes from a text file using comma as a delimiter everything was working fine, but now when I debug I get the "Index out of range exception was unhandled" warning. I guess I need a fresh pair of eyes to see where I went wrong, I commented on the line that gets the error //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
9
  • Such a long code. At least give some callstack Commented Jun 7, 2010 at 16:19
  • Can you run it in the debugger and see what "fields" is when you try to access "fields[1]"? Commented Jun 7, 2010 at 16:19
  • Start debugging by inserting Debug.Assert( fields.Length == 6 ) after the split Commented Jun 7, 2010 at 16:21
  • 1
    Any blank lines in the file? Why not use the debugger to see the line causing the error? Commented Jun 7, 2010 at 16:21
  • 2
    @Michael: All of the other fields will still be filled in from the previous iteration - the fact that Lname is "" suggests that you've got a blank line in the file, as suspected elsewhere. (Note that declaring the local variables inside the loop would make this clearer, as you wouldn't have the variables from the previous iteration confusing things.) Commented Jun 7, 2010 at 16:27

5 Answers 5

5

For the sake of anyone who doesn't want to look at the mammoth code you've posted, here's the relevant bit:

while (recordIn != null)
{

    fields = recordIn.Split(DELIM);
    Lname = fields[0];
    Fname = fields[1]; // this is where the error appears

Given the exception you've seen, that basically means that recordIn doesn't contain the delimiter DELIM (a comma). I suggest you explicitly check for the expected size and throw an exception giving more details if you get an inappropriate line. Or if it's a blank line, as others have suggested (and which does indeed seem likely) you may want to just skip it.

Alternatively, here's a short but complete console application which should help you find the problem:

using System;
using System.IO;

class Test
{
    static void Main()
    {
        string[] lines = File.ReadAllLines("source\\Staff.txt");
        for (int i = 0; i < lines.Length; i++)
        {
            string line = lines[i];
            string[] fields = line.Split(',');
            if (fields.Length != 6)
            {
                Console.WriteLine("Invalid line ({0}): '{1}'",
                                  i + 1, line);
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

That could be because of blank line that appear at the top in the text file.

Comments

1

Have you checked for an empty row at the end of your text file?

Comments

1

After this:

fields = recordIn.Split(DELIM);

you need this:

if (fields.length < 6)
{
    // the current recordIn is the problem!
}
else
{
    Lname = fields[0];
    // etc.
}
recordIn = reader.ReadLine(); // make sure to put this after the else block!

You should do this routinely when reading from files, because there are often leading or trailing blank lines.

Comments

0

You've most likely got an extra blank line at the end of your input file, which therefore only has one (empty) field, giving you index out of range at index 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.