C#IndexOutOfRange问​​题,可能很简单

时间:2010-05-13 21:51:23

标签: c# indexing range

由于这个原因,我把头撞到了墙上。我在cell [rcell] = repack [counter]收到错误,即使我在重新包装数组中有190个项目。

        private string csvtogrid(string input)
    {
        input = input.Replace("\r", ",").Substring(2).TrimEnd(',').Trim().Replace("\n", ",").Replace(",,,", ",").Replace(",,",",");
        string[] repack = input.Split(',');
        string[] cell = { };
        int rcell = 1;
        for (int counter = 1; counter < repack.Length; counter++)
        {
            if (rcell < 4)
            {
                cell[rcell] = repack[counter];
                rcell++;
            }
            procgrid.Rows.Add(cell[1], cell[2], cell[3]);
            rcell = 1;
        }
        richTextBox1.Text = input;
        return null;
    }

1 个答案:

答案 0 :(得分:2)

您的cell数组为空,因此无法分配给元素cell[rcell],因为它不存在。

string[] cell = { };

初始化时,您应该给它一个足够大的尺寸:

string[] cell = new string[4];