Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how do I bind an array to DataGridView such that the values in the array are displayed?

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?

like image 633
phan Avatar asked Dec 04 '25 23:12

phan


1 Answers

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.

like image 117
LarsTech Avatar answered Dec 07 '25 14:12

LarsTech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!