3

I'm using Visual C# 2010 Express. I have an Array of strings like this arr[100][2]. Here's my 3 lines of code

 string FilePath = @"c:\data.txt";
 var arrData = File.ReadLines(FilePath).Select(line => line.Split('\t')).ToArray();
 dataGridView1.DataSource = arrData;

When I run the code I see 7 column headers in the DataGridView control instead of the contents of my array: Length, LongLength, Rank, SyncRoot, IsReadOnly, IsFixedSize, and IsSynchronized. What is this?

Somehow, I am displaying the attributes of the array instead of the values actually contained inside of the array.

I know there are legit values in the array because when I step through the code I can clearly see the contents (names and ages). What am I doing wrong?

3
  • Could you say what is your application? Is it asp.net, wpf or something else? Commented Sep 6, 2012 at 15:49
  • It's a WindowsFormsApplication. And these are the only lines of code (attached to a button click event). Commented Sep 6, 2012 at 15:50
  • Also, please consider using a CSV / TSV library rather than writing your own code. I put my tiny minimalist unit-tested library here: code.google.com/p/csharp-csv-reader Commented Sep 6, 2012 at 16:18

2 Answers 2

2

Try converting to a list of "objects" first. I created a test file with a first name, last name and an age all separated by a tab to test:

string FilePath = @"c:\data.txt";
var arrData = File.ReadLines(FilePath).Select(line => 
                                              line.Split('\t')).ToArray();

var query = from x in arrData
            select new { FirstName = x[0], LastName = x[1], Age = x[2] };

dataGridView1.DataSource = query.ToList();

I would think what you are attempting would be fairly error prone. I would consider first converting the file to an actual list of objects first.

Sign up to request clarification or add additional context in comments.

Comments

0

Can you just make your arrData a List instead. So it would be this instead:

 string FilePath = @"c:\data.txt";
 var arrData = File.ReadLines(FilePath).Select(line => line.Split('\t')).ToList();
 dataGridView1.DataSource = arrData;

This should be all you need to do. Also, be sure to make sure that your arrData actually has data in it too :)

2 Comments

Same result as ToArray() actually.
@Chris. Hi. Changing it to a list with ToList() had absolutely no effect. Same results. It doesn't display what's inside my List, but instead showed what I mentioned above. And yes, I can see that arrData has data in it. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.