jan
jan

Reputation: 1601

DataGridView - DataTable - displaying properties

( .NET 2.0, System.Windows.FormsDataGridView and DataTable )

I have 1 datagrid connected to 1 datatable.

That datatable contains 1 column: containing objects of my own type "MyObject".
MyObject has a public string property "MyProp".

I want to display 1 column in the grid: showing the string values of the property MyProp of the MyObjects in the table.

But I can't seem to get it to work.

Schematically:

Column.DataPropertyName="Obj" (generated by default)

Displays the result of (overridden) MyObject.ToString() Not really what I want, this function is in use for logging.

GridViewColumn.DataPropertyName="Obj.MyProp"

Doesn't display anything (MyProp's get is never called)

In short:

GridViewColumn.DataPropertyName doesn't seem to support drilling further down into objects in a datatable's column.

Anyone any ideas?

Thanks in advance!

Jan

Upvotes: 0

Views: 1543

Answers (3)

mson
mson

Reputation: 7824

This can be done via OnRowDataBound event.

In the gridview

  1. declare an onrowdatabound method

  2. use template

In the method:

  1. grab object

  2. populate or manipulate display as desired

You can also do what you want by using templates instead of default layout.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062520

You can only bind to immediate properties of the data-source. For DataTable, this means columns. Two options leap to mind:

  • don't use DataTable - just use a List<MyObject> or BindingList<MyObject>
  • (or) override MyObject.ToString() to return MyProp

The second isn't very flexible - I'd go with the first. After all, what is a 1-column DataTable really doing for you?

Upvotes: 0

StingyJack
StingyJack

Reputation: 19459

Try just putting the Obj.MyProp string value into the datatable row. Putting an object into there will require it to be converted into a string representation (Obj.ToString()) which is getting you the output you are seeing.

A datatable is much like a spreadsheet, not like an Array(Of objects). You have to treat it as such,.

Upvotes: 1

Related Questions