I keep getting this error I can not figure out why
IndexOutOfRangeException exception is thrown
Here is the code can someone help
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication19
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string line;
string[] row = new String[3];
StreamReader file = new StreamReader("c:\\dell\\first.txt");
while ((line = file.ReadLine()) != null)
{
row = line.Split(',');
textBox2.Text += (row[1]);
textBox3.Text += (row[2]);
}
file.Close();
}
}
}
Loading
theLizardPosted Jul 5, 2010, 8:42 PM
with the text file, I have run your example, the error occurs at line 2 where you have textBox3.Text += (row[2]);
As I said, if index 2 does not exist then you will get this error.
row.Length returns the number of elements in the array, if the length is 2 then the 1st index into the array is 0 the next is 1 and so on.
nigel drakesPosted Jul 5, 2010, 7:30 PM
theLizardPosted Jul 5, 2010, 5:52 PM
textBox2.Text += (row[1]);
textBox3.Text += (row[2]);
This means that you are attempting to access an element that does not exist, this could be because the line you are reading in from the text file cannot be split into the number of elemnts you are expecting.
you need to check the length of row --> if(row.Length >= 2) {textBox2.Text += (row[1]); textBox3.Text += (row[2]);} or other ways of doing same.
Another thing is that you may have the right number of elements but array indexes start at 0 so if you do have 2 elements after reading in a line the error would come from here textBox3.Text += (row[2]);
try this
textBox2.Text += (row[0]);
textBox3.Text += (row[1]);