Reputation: 2832
Although there are a lot of posts on this site about populating a gridview with objects, I can't get it working.
I have a class called Logs with 3 public properties - Time, Description and Error. There is also a public property called logList that will return a List of Logs Objects.
And I have DataGridView in my WinForm, called myGV, with 3 columns called Time, Description and Error.
So I'm trying:
myGV.DataSource = Logs.logList.OrderBy(x => x.Time);
But my DataGridView displays nothing, even though logList does contain data.
Thanks for your work on this site!
UPDATE: If I remove all columns from myGV it does display data. So how do match static columns to the properties in my List of Objects?
Upvotes: 1
Views: 11072
Reputation: 51
OrderBy() returns IOrderedEnumerable<> type of data, that are not bindable to DataGridView.
So you have to cast them to a Binding Source.
Use ToList() method like
"OrderBy().ToList()" to bind your gridview.
dataGridView1.DataSource = studList.OrderBy(a => a.Age).ToList();
It is working
For more info to bind DataGridView visit dataGridView binding
Upvotes: 0
Reputation: 63317
It's strange that you said If I remove all columns from myGV it does display data...
. I reproduced your problem and the reason is your LINQ
query is not executed. You have to call ToList()
or similar method before using the result as DataSource
of your DataGridView
:
myGV.DataSource = Logs.logList.OrderBy(x => x.Time).ToList();
Of course, If your static columns don't have DataPropertyName
matched with the properties of the DataSource, there will be more columns added to your DataGridView
than you expect. For example, suppose all the Time
, Description
and Error
are added at design time without assigning any DataPropertyName
and yourDataGridView.AutoGenerateColumns = true
(by default), if you assign the DataSource
of your DataGridView
as above, your DataGridView
may have 6 columns at all, instead of 3. So you can assign the DataPropertyName
of your added columns before assigning the DataSource
for your DataGridView
, something like this:
myGV.Columns["Time"].DataPropertyName = "Time";
myGV.Columns["Description"].DataPropertyName = "Description";
myGV.Columns["Error"].DataPropertyName = "Error";
myGV.DataSource = Logs.logList.OrderBy(x => x.Time).ToList();//This should be called at here after all the DataPropertyNames are initialized.
I recommend you to set myGV.AutoGenerateColumns = true
(by default) and remove all the added columns, just let the DataGridView
auto-generate columns for you.
Upvotes: 3
Reputation: 17370
After you manually add the columns, you have to make sure you update the DataPropertyName
of each one of them:
DataPropertyName
and change them to Date
, Error
and Description
and whatever other names you have used for your columns.
Make sure these match with your Properties
in your Logs class.
Upvotes: 3