【问题标题】:Show Attribute of Relation in DataGridView在 DataGridView 中显示关系的属性
【发布时间】:2009-08-27 06:57:42
【问题描述】:

我想在 DataGridView 中显示关系的属性。我使用 LINQ to SQL 进行映射并具有以下类:

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

class User
{
    public string Name;
}

我使用 DataGridView 显示 Computer 实体的一些行,并且还希望有一列显示与这台计算机关联的用户的名称。

我创建了Computer 类的对象数据源。我已将 BindingSource 的 DataSource 属性设置为此数据源,并将我的 DataGridView 与此 BindingSource 链接。我在 DataGridView 中添加了一列并将 DataPropertyName 属性设置为 //User.Name//,但这不起作用。有什么好的方法可以做到这一点?

我已经考虑过创建一个额外的类,它继承自Computer,并有一个额外的字符串属性表示用户名;但我想避免这种解决方案。

【问题讨论】:

    标签: c# winforms linq datagridview


    【解决方案1】:
    var computerUsers = from c in mydataContext.Computer
    select new {
     computerName = c.Name,
     userName = c.User.Name
    };
    
    myDataGridView.datasource = computerUsers;
    myDataGridView.dataBind();
    

    并在您的 datagridview 中调用“computerName”和“userName”

    <asp:BoundField DataField="computerName" HeaderText="Computer" />
    <asp:BoundField DataField="userName" HeaderText="User" />
    

    【讨论】:

    • 我已经考虑过使用匿名类的解决方案,但如果可能的话,我喜欢使用 GUI 设计。
    • 你到底想要什么代码?我使用 GUI 设计器来定位我的控件,您要编写设计器生成的代码吗?
    • oops.did 没有看到 windows-forms 标签。它的工作方式与 web-forms 相同吗?像 aspx 文件和文件背后的代码?对不起。不熟悉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多