views:

485

answers:

3

( .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:

  • myTable.Column1.Name: "Obj"
  • myDataSet contains 1 table: myTable (filled with a few rows)
  • myBindingSource.datasource = myDataSet
  • myBindingSource.DataMember = myTable
  • myDataGridView.DataSource = myBindingSource
  • in myDataGridView: 1 DataGridViewTextBoxColumn

  • tryout 1:

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.

  • tryout 2:

GridViewColumn.DataPropertyName="Obj.MyProp"

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

  • tryout 3: Made the MyProp property bindable:

    [Bindable (BindableSupport.Yes)]
    public string MyProp
    { ...
    

    Samesame, not different from tryout 2

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

+1  A: 

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,.

StingyJack
A: 

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?

Marc Gravell
i tried using list<myObject> but i became confused in applying it to the nested class... for single level of class it works fine
KoolKabin
A: 

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.

mson
I think he's referring to a DataGridView, not a web DataGrid. If memory serves correct, the DGV doesn't have a OnRowDataBound event.
BFree