hanzi_ru hanzi_ru - 2 months ago 8
C# Question

Insert an Array to a datagidview

I have written a coding which extracts specific lines from a text file, split the lines and insert the data to a gridview. The coding is give below.

Unfortunately, when i execute this program, i receive an error msg called "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index". Please help me to identify what went wrong in my codings

string line;
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");

while ((line = file.ReadLine()) != null)
{
if (line.Contains("DISKXFER"))
{
string dataLine=line.ToString();
string[] split = dataLine.Split(',');
for (int i = 0; i < split.Length; i++)
{
for (int j = 1; j < dataLine.Length; j++)
{
dataGridView1.Rows[j].Cells[i].Value = split[i];
}
}
}
}

Answer

Your DataGridView does not contain the number of rows required to hold the information. Instead of setting dataGridView1.Rows[j].Cells[i] to some value, you need to add one row for every entry in dataLine.

Instead of your nested loop you could do this:

string dataLine=line.ToString();
string[] split = dataLine.Split(',');

dataGridView1.Rows.Add(split);