Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

Index was out of bounds of array? c# forms

I'm trying to read the following textfile:(skipping first 8 lines) And reading from arrow each column enter image description here

And am doing so by putting each column value in an array which is dictated by position and length

To test if the array value actually captured a column value I want to see the value[0] when I click another button. But when I run my app, I get the error that my index was out of bounds of the array? How, when my array size is 3 and I don't go beyond that.

    string[] val = new string[3 ]; // One of the 3 arrays - this stores column values

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {

            string[] lines = File.ReadAllLines(ofd.FileName).Skip(8).ToArray();
            textBox1.Lines = lines;

             int[] pos = new int[3] { 3, 6,18}; //setlen&pos to read specific clmn vals
             int[] len = new int[3] {2, 10,28}; // only doing 3 columns right now



             foreach (string line in textBox1.Lines)
             {
                 for (int j = 0; j <= 3; j++)
                 {
                     val[j] = line.Substring(pos[j], len[j]); // THIS IS WHERE PROBLEM OCCURS
                 }

             }

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {   // Now this is where I am testing to see what actual value is stored in my    //value array by simply making it show up when I click the button.

        MessageBox.Show(val[0]);
    }
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

arrays are 0 indexed, that means that an array with 3 elements will have elements at indexes 0, 1, and 2.

3 is out of bounds, so when you try to access pos[3] or len[3], your program will thrown an exception.

use j < 3 instead of j<=3

 for (int j = 0; j < 3; j++)
 {
     val[j] = line.Substring(pos[j], len[j]); // THIS IS WHERE PROBLEM OCCURS
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...