且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以将复杂类型的属性绑定到数据网格?

更新时间:2022-10-14 22:43:11

好吧...通过在 cell_formatting 事件中使用反射来检索嵌套属性来执行此操作的简单方法.

是这样的:

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

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;}
}

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?

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

Goes like this:

    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;
        }
    }

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