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];
}
}
}
}
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);
This page show you an example http://www.dotnetperls.com/convert-list-datatable, for more information about datagridview http://www.dotnetperls.com/datagridview
Related
I have a piece of code that is supposed to streamread this text file:
1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
1.1.1.2.2.2.2.1.1.1.2.2.1.1.1
1.2.2.2.2.2.2.2.2.2.2.2.2.1.1
1.1.2.2.2.2.2.2.2.2.2.2.2.1.1
1.1.2.2.2.2.2.2.2.2.2.2.1.1.1
1.1.1.1.2.2.2.2.2.2.2.2.1.1.1
1.1.1.1.2.2.2.2.2.2.1.1.1.1.1
1.1.1.1.1.1.2.2.2.1.1.1.1.1.1
1.1.1.1.1.1.1.2.1.1.1.1.1.1.1
1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
1.1.1.1.1.1.1.1.1.1.2.2.1.1.1
1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
Everything is going fine, kinda of. My purpose was to rummage through all the characters one by one, then after that's done start on a new line. This is where my little problem occurs, which I've been trying to fix all night.
It reads the first line nicely, but then it doesn't read the second line...
Here is the code:
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Text\TextFile.txt");
int loadX = 0;
int loadY = 0;
string line;
while (true)
{
if (loadX <= 12)
{
loadX++;
while ((line = file.ReadLine()) != null)
{
System.Threading.Thread.Sleep(500);
string[] entries = line.Split('.');
System.Console.Write(entries[loadX]);
loadY++;
}
}
System.Threading.Thread.Sleep(500);
Console.Write($" Finished {loadX}");
loadX = 0;
}
var lines = File.ReadAllLines(#"C:\Text\TextFile.txt");
var points = lines.SelectMany((l, x) => l.Split('.').Select((s, y) => new {X = x, Y = y, Value = s}));
foreach (var point in points)
{
Console.WriteLine($"({point.X}, {point.Y})={point.Value}");
}
Using a while loop and StremReader seems so silly when you have easier and more readable ways of handling this.
You can easily simplify your code by doing File.ReadAllLines()
//lines will be a string array
var lines = File.ReadAllLines(#"C:\Text\TextFile.txt");
for(int x = 0; x < lines .Length; x++)
{
var cols = lines [x].Split('.');
for(int y = 0; y < cols.Length; x++)
{
//Here you have access to the value, and the x and y position
Console.WriteLine("x: {0}, y: {1} value: {2}", x, y, cols[y]);
}
}
Demo here
If you want to go through every number in this file with X and Y then this is an example how you can do so:
string[] lines = File.ReadAllLines(#"C:\Text\TextFile.txt");
for(int indexY = 0; indexY < lines.Length; indexY++){
string[] lineEntries = lines[indexY].Split('.');
for(int indexX = 0; indexX < lineEntries; indexX++){
// here you have one number by accessing
// it with lineEntries[indexX]
Console.Write(lineEntries[indexX]);
}
Console.WriteLine();
}
You are mistaken to think it is reading the first line. In fact, your current code reads the first value of each line. Due to your input this just happens to be a similar output to what the first line would be, which has lead to your confusion.
Your main loop should be looping through each line, then you can process the line and loop through each value. Which you can then use however you want.
Here is an example:
using(System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Text\TextFile.txt"))
{
int loadX = 0;
int loadY = 0;
string line;
// Loop through each line as you read it.
while ((line = file.ReadLine()) != null)
{
// Split the line to get an array of values.
string[] entries = line.Split('.');
// Loop through each value and process.
for(int i = 0; i < entries.length; i++)
{
string entry = entries[i];
// TODO: Do something with entry.
loadY++;
}
loadX++;
}
}
Obviously in this example loadX and loadY are not being used, but this demonstrates how to correctly increment them so you can use them as needed.
TIP: When using a SteamReader you should ensure you dispose of it correctly, this is best done by including it in a using block.
I am trying to parse a column (File is composed of only 1 column filled with double numbers.) in a .csv file but C# throws me error when it encounters an empty cell.
{"Input string was not in a correct format."}
I want program to continue with the next cell when this happens. Is there a way?
Note: I tried
if(array[i] != null)
but this does not seem to work.
I use this block to read from .csv:
var column = new List<string>();
using (var rd = new StreamReader(#"pathofthecsvfile"))
{
while (!rd.EndOfStream)
{
var splits = rd.ReadLine().Split(';');
column.Add(splits[0]);
}
}
string[] arr = column.ToArray();
double[] array = new double[arr.Length];
//problem is in this block
for (int i = 0; i < array.Length; i++)
{
if (arr[i] != null)
{
array[i] = Convert.ToDouble(arr[i]);
}
}
I would check it when inserting:
if split[0] != null && split[0] != "" {
column.Add(splits[0]);
}
You are not validating the data you are loading into the array to see if it is in a valid format - Convert.ToDouble will fail for a number of reasons other than just null value and empty string.
If you are happy just to skip to next column, use a TryParse instead in the for loop:
double.TryParse(arr[i], out array[i]);
I'm trying to read data from a file, split the data and save to array. The code works fine except for the split. It is returning a NullException.
Any help would be greatly appreciated.
public static void LoadHandData(CurrentHand[] handData, string fileName)
{
string input = ""; //temporary variable to hold one line of data
string[] cardData; //temporary array to hold data split from input
StreamReader readHand = new StreamReader(fileName);
for (int counter = 0; counter < handData.Length; counter++)
{
input = readHand.ReadLine(); //one record
cardData = input.Split(' '); //split record into fields
int index = 0;
handData[counter].cardSuit = Convert.ToChar(cardData[index++]);
handData[counter].cardValue = Convert.ToInt16(cardData[index++]);
}
readHand.Close();
}
As per the comments, you've only got one line of data. But look at your loop:
for (int counter = 0; counter < handData.Length; counter++)
{
input = readHand.ReadLine(); //one record
cardData = input.Split(' '); //split record into fields
int index = 0;
handData[counter].cardSuit = Convert.ToChar(cardData[index++]);
handData[counter].cardValue = Convert.ToInt16(cardData[index++]);
}
That's trying to read one line per hand. On the second iteration, ReadLine will return null, so when you call input.Split() you'll end up with the NullReferenceException you're seeing.
You need to read the line once and split it. Given that you've only got one line of text, you can just use File.ReadAllText to simplify things:
string input = File.ReadAllText(fileName);
string[] cardData = input.Split(' ');
for (int counter = 0; counter < handData.Length; counter++)
{
handData[counter].cardSuit = Convert.ToChar(cardData[counter * 2]);
handData[counter].cardValue = Convert.ToInt16(cardData[counter * 2 + 1]);
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
printing 2d array in c# through for loop
this is how my data in txt file:
1--2--3--
3-4-4-5--
-7-3-4---
7--5--3-6
--7---4--
3-2--4-5-
------3--
2-6--7---
4---4--3-
without any empty line between! have this formatting issue above!
is my c# code to do file reading with the display too:
public void populate_grid_by_file()
{
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("data.txt");
for (int i = 0; i < Sodoku_Gri.GetLength(0); i++)
{
while ((line = file.ReadLine()) != null)
{
for (int j = 0; j < Sodoku_Gri.GetLength(1); j++)
{
Sodoku_Gri[i,j] = line[j];
Console.Write(line[j].ToString());
}
Console.WriteLine(line);
counter++;
}
}
file.Close();
// Suspend the screen.
Console.ReadLine();
}
but when i display my array with the file reading above it is like:
1--2--3--1--2--3--
3-4-4-5--3-4-4-5--
-7-3-4----7-3-4---
7--5--3-67--5--3-6
--7---4----7---4--
3-2--4-5-3-2--4-5-
------3--------3--
2-6--7---2-6--7---
4---4--3-4---4--3-
cnt understand why duplication! help!
When i debugged i found that there was a problem in the line:
Console.Write(line[j].ToString());
it means that automatically elements are not being loaded into the array here:
Sodoku_Gri[i,j] = line[j];
Kindly help me with this!
You display the line once, character by character here:
Console.Write(line[j].ToString());
And then the full line all at once here:
Console.WriteLine(line);
I am parsing my data output, however, my data has return charicters in it (\n). So when I run my code, the array is built and one of the arrays (4) is blank data... I have tried using null, "", and " ". Would anyone know how I can prevent that last array from showing?
char[] returnChar= {'\n' };
string parseText = captcha;
string[] words = parseText.Split(returnChar);
int count = words.Length;
for (int i = 0; i < count; i++)
{
if (words[i] == null)
{
MessageBox.Show("This row is empty: " + i);
}
MessageBox.Show(words[i]);
}
When doing String.Split, define the second parameter - StringSplitOptions.
string[] words =
parseText.Split(returnChar, StringSplitOptions.RemoveEmptyEntries);
This way it will skip over empty elements.