views:

213

answers:

1

I want to show the attribute of a relation in a DataGridView. I use LINQ to SQL to do the mapping and have the following classes:

class Computer
{
    public string Name;
    public User User;
}

class User
{
    public string Name;
}

I use a DataGridView to show some rows of the Computer entity and also want to have one column to show the name of the user associated with this computer.

I've created an object data source of the Computer class. I've set the DataSource property of my BindingSource to this data source and linked my DataGridView with this BindingSource. I've added a column to my DataGridView and set the DataPropertyName property to //User.Name//, but this does not work. What is a good way to do this?

I've already thought about creating an additional class which inherits from Computer and has an additional string property which represents the name of the user; but I want to avoid this solution.

+2  A: 
var computerUsers = from c in mydataContext.Computer
select new {
 computerName = c.Name,
 userName = c.User.Name
};

myDataGridView.datasource = computerUsers;
myDataGridView.dataBind();

and in your datagridview call "computerName" and "userName"

<asp:BoundField DataField="computerName" HeaderText="Computer" />
<asp:BoundField DataField="userName" HeaderText="User" />
krishna
I've already thought about the solution with anonymous classes, but I like to use the GUI Design if possible.
Manuel Faux
ok. can you post your datagrid and objectsource code?
krishna
What code do you want exactly? I use the GUI designer to position my controls, do you want to code the Designer has generated?
Manuel Faux
oops.did not see the windows-forms tag.Does it work the same as web-forms? like a aspx file and a code behind file?Sorry.Not familiar
krishna