PDA

Click to See Complete Forum and Search --> : [2.0] DataGridView Objects Probs.


Rauland
Jun 7th, 2007, 11:11 AM
Hi
Suppose I have a Class Person, with a property "Surname".

I have a dataTable such as:

DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Surname",typeof(Person));
dt.Columns.add(dc);

Create an Instance of Person:

Person prs = new Person();
prs.Surname = "Rauland";

I now, create a dataRow:

DataRow dr = dt.CreateRow();
dr["Surname"] = prs;

dt.rows.add(dr);

I now use this dataTable as a dataSource to a dataGridView, named dbTest;

This grid has a column named, "Surname".
And have set the DataPropertyName to "Surname".(Meaning that it will display in this column the DataTableīs column with name "Surname")
dbTest.DataSource = dt;

The only thing it displays the type of object, in this case, Person.
Is there a way to set what in other controls is called "DisplayMember", the DataTablesīs column named "Surname", to display the Personīs property "Surname".

Thanks!!

jmcilhinney
Jun 7th, 2007, 06:14 PM
You've got a DataRow with a column named "Surname", yet you're assigning an entire Person object to it:dr["Surname"] = prs;If you want that column to contain a surname then you need to assign the Surname property of the Person to it, not the whole Person.

Rauland
Jun 11th, 2007, 07:04 AM
Hi Thanks jmcilhinney,
YOur right, I only had to assign the Surname Property.

But certain controls, have a display member, that you can use ,to make it display the property your intersted in.

ComboBoxes, etc,... set the DisplayMember to "SurnameName", assign a List of Person Objects to it and the control knows which property to display, in this case "Surname".

I was just asking my self if there was a property, similiar to DisplayMember, but for DataColumns(which arenīt controls, or are they?? :o ). So I could add the whole object, and get it to display the name.

I think I can define datacolumns,defining the type it will accept;

DataColumn dc = new DataColumn("Surname",typeof(Person));

Doing it the way you suggested solved the problem, but, in that case the datacolumn would accept strings Person.Surname. Which isnīt a great problem, but would of been nice to have person objects, so any work I did on the column would be with person objects not strings.

Maybe Iīm over complicating things,..
Thanks
Rauland

mendhak
Jun 11th, 2007, 03:39 PM
Then you probably want to override the ToString() method and have it return the surname property.

jmcilhinney
Jun 11th, 2007, 07:19 PM
What mendhak says is quite correct, but I don't really see why you would want a Person object in a column anyway. In that case it sounds to me like you should have two DataTables related by the ID of a Person record.