可以将复杂类型的属性绑定到datagrid吗? [英] Is it possible to bind complex type properties to a datagrid?

查看:130
本文介绍了可以将复杂类型的属性绑定到datagrid吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下对象绑定到一个gridview?

How would I go about binding the following object, Car, to a gridview?


public class Car
{
   long Id {get; set;}
   Manufacturer Maker {get; set;}
}

public class Manufacturer
{
   long Id {get; set;}
   String Name {get; set;}
}

原始类型容易绑定,但我没有找到任何方式可以为Maker显示任何内容。我希望它显示Manufacturer.Name。甚至有可能吗

The primitive types get bound easy but I have found no way of displaying anything for Maker. I would like for it to display the Manufacturer.Name. Is it even possible?

这样做会是什么?我必须在Gar车中存储ManufacturerId,然后在制造商列表中设置一个lookupEditRepository?

What would be a way to do it? Would I have to store ManufacturerId in Car as well and then setup an lookupEditRepository with list of Manufacturers?

推荐答案

Allright guys ...这个问题被发贴waaay回来,但我刚刚发现一个相当不错的&简单的方法是通过在cell_formatting事件中使用反射来检索嵌套的属性。

Allright guys... This question was posted waaay back but I just found a fairly nice & simple way to do this by using reflection in the cell_formatting event to go retrieve the nested properties.

如下所示:

    private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {

        DataGridView grid = (DataGridView)sender;
        DataGridViewRow row = grid.Rows[e.RowIndex];
        DataGridViewColumn col = grid.Columns[e.ColumnIndex];
        if (row.DataBoundItem != null && col.DataPropertyName.Contains("."))
        {
            string[] props = col.DataPropertyName.Split('.');
            PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]);
            object val = propInfo.GetValue(row.DataBoundItem, null);
            for (int i = 1; i < props.Length; i++)
            {
                propInfo = val.GetType().GetProperty(props[i]);
                val = propInfo.GetValue(val, null);
            }
            e.Value = val;
        }
    }

就这样!您现在可以在列的DataPropertyName中使用熟悉的语法ParentProp.ChildProp.GrandChildProp。

And that's it! You can now use the familiar syntax "ParentProp.ChildProp.GrandChildProp" in the DataPropertyName for your column.

这篇关于可以将复杂类型的属性绑定到datagrid吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆