错误:索引超出了c#中数组的范围 [英] error:index was outside the bounds of the array in c#

查看:107
本文介绍了错误:索引超出了c#中数组的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,

美好的一天,

我有读者文本文件,但文件长度不是静态

我的代码是:

Dear all,
Good day,
I have reader text file but the length of file not static
my code is :

public class jr
        {




            public string name1 { get; set; }
            public string name2 { get; set; }
            public string name3 { get; set; }
            public string name4 { get; set; }
            public string name5 { get; set; }
            public string name6 { get; set; }
            public string name7 { get; set; }
            public string name8 { get; set; }
            public string name9 { get; set; }
           

            public static List<jr> LoadUserListFromFile(string path)
            {


                var users = new List<jr>();


                foreach (var line in File.ReadAllLines(path))
                {

               


                    var delimiters = new char[] { ',' };

                    var columns = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                    users.Add(new jr




                    {

                        name1 = columns[0].Trim(),
                        name2 = columns[1].Trim(),
                        name3 = columns[2].Trim(),
                        name4 = columns[3].Trim(),
                        name5 = columns[4].Trim(),
                        name6 = columns[5].Trim(),
                        name7 = columns[6].Trim(),
                        name8 = columns[7].Trim(),
                        name9 = columns[8].Trim(),
                       
                    }

                );

                }
                return users;

            }

        }







to在datagridview中读取它:






to read it in datagridview :

dataGridView1.DataSource = jr.LoadUserListFromFile("file path");






$ b我可以读取的一些文件的$ b但我收到的另一个文件错误索引超出了数组的界限

因此我需要使我的代码动态而不是特定文件的静态。

我的意思是检查文件的长度并创建列长度



我希望每件事都清楚。

感谢您的帮助。




for some of files i can read but another files i received error index was outside the bounds of the array
so i need to make my code dynamic not static for specific files.
I mean like check the length of file and create columns as the length

I hope every things is clear.
Thank you for your help.

推荐答案

您假设列的索引0到8可用。也许首先检查是否使用 columns.Length



祝你好运!
You assume columns has index 0 to 8 available. Maybe check first if this is the case using columns.Length.

Good luck!


这篇关于错误:索引超出了c#中数组的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆