Share via


C# DataGridView on WinForm - index was out of range

Question

Wednesday, November 27, 2019 5:43 AM

I have a tab delimited file and want to import into DataGridView

However, I got an error due to "Index was out of range", I dig into the code and unable to find any problems.

Could somebody provide me some help here?

        private void LoadTabData(string[] lines)
        {
            int i = 0;
            int j = 0;

            foreach (string line in lines)
            {
                // Split the line
                string[] array = line.Split(new Char[] { '\t' });

         

                if (i == 0)
                {
                    this.FormatGrid(array);
                }
                else
                {
                    grid.Rows.Add();

                    for (j = 0; j < array.Length; j++)
                    {
                        grid[j, i].Value = array.GetValue(j); // < ERROR right here (index was out of range)
                    }
                }

                i++;
            }
        }

All replies (4)

Wednesday, November 27, 2019 6:20 AM

Have you verified that you are not trying to set value on column (or row) at index that does not exists?

Also the DataGridViewRowCollection.Add method returns you the row index of the added row so you can use that to make sure you access added row.


Wednesday, November 27, 2019 9:16 AM

Hi Ihandler MSDN, 

Thank you for posting here.

According to your question, I try to make a test, but I need more information.

Could you provide some related code about ‘FormatGrid’ and more details about your datagridview? It will help us to make a test and reproduce your problem.

We are waiting for your update.

Best Regards,

Xingyu Zhao

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Wednesday, November 27, 2019 9:20 AM

Hi,

Try to add one line code to show the value of "i" and "j", just above the error line, and see how it changes.

Regards,

Ashidacchi -- http://hokusosha.com


Wednesday, November 27, 2019 11:37 AM

Hello,

If open to a alternate way to do this.

Full source code.

Note if you are new to coding the event aspects of the code may be new to you so take time to not just try and use the code but instead understand the code. Also note it's best to keep file operations out of the form, in a class which is why I used a class in the first place.

In the following example there are three predefined DataGridView columns to populate. Then the tab delimited file which in this case resides in the same folder as the project's executable.

First Last    Account
Alana   Petty   AF7Y7
Patricia    Cooke   B60BI
Jami    Browning    UY99GB  Indianapolis

Stacey  Cuevas

Lamont  Mendez  GFF8FFZ Aurora  Minnesota   Cook Islands    9264.14
Duane       Blevins

The class below reads data from the file above, on the first line an event is triggered which back in the form the instance of the class has subscribed too (in the event I simply show the array via string.Join which in your case would do something other than this).

Note you need to change the namespace to your namespace from what I have and you are good.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ForumQuestionTabbed
{
    public class FileOperations
    {
        public delegate void LineHandler(object sender,LineDataArgs myArgs);
        public event LineHandler OnLineHandler;

        public List<string[]> ReadLines(string fileName)
        {
            var linesList = new List<string[]>();

            if (!File.Exists(fileName))
            {
                return linesList;
            }

            string line;
            var isFirstLine = true;

            using (var reader = new StreamReader(fileName))
            {

                while (!reader.EndOfStream)
                {
                    line = reader.ReadLine();

                    if (isFirstLine)
                    {
                        isFirstLine = false;
                        if (!string.IsNullOrWhiteSpace(line))
                        {
                            var lineDataArgs = new LineDataArgs(Array.ConvertAll(line.Split('\t'), p => p.Trim()));
                            OnLineHandler(this, lineDataArgs);
                        }

                        continue;
                    }

                    if (string.IsNullOrWhiteSpace(line)) continue;

                    var parts = Array.ConvertAll(line.Split('\t'), p => p.Trim());

                    if (parts.Length <= 3)
                    {
                        linesList.Add(parts);
                    }
                    else if (parts.Length > 3)
                    {
                        linesList.Add(parts.Take(3).ToArray());
                    }
                    
                }

            }

            return linesList;
        }

    }
    public class LineDataArgs : EventArgs
    {
        protected string[] Line;

        public LineDataArgs(string[] sender)
        {
            Line = sender;
        }
        public string[] LineArray => Line;
    }
}

Form code

using System;
using System.IO;
using System.Windows.Forms;

namespace ForumQuestionTabbed
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Shown += Form1_Shown;
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Import1.txt");

            var fileOperations = new FileOperations();
            fileOperations.OnLineHandler += FileOperations_OnReadingFirstLine;

            var data = fileOperations.ReadLines(fileName);

            foreach (var rowData in data)
            {
                dataGridView1.Rows.Add(rowData);
            }
        }
        private void FileOperations_OnReadingFirstLine(object myObject, LineDataArgs args)
        {
            Console.WriteLine(string.Join(",",args.LineArray));
        }
    }
}

Note some columns are empty, that is because there is no data, go back and look at the sample text file.

Lastly, keep in mind this is a working example with three columns and you may have some differences like more columns, apply the same logic used in the code above to work this out for your requirements.

Hope this is of use to you.

Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

NuGet BaseConnectionLibrary for database connections.

StackOverFlow