Is it possible to bind complex type properties to a datagrid?

前端 未结 8 723
时光取名叫无心
时光取名叫无心 2020-12-02 15:55

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         


        
相关标签:
8条回答
  • 2020-12-02 16:45

    I would assume you could do the following:

    public class Car
    {
        public long Id {get; set;}
        public Manufacturer Maker {private get; set;}
    
        public string ManufacturerName
        {
           get { return Maker != null ? Maker.Name : ""; }
        }
    }
    
    public class Manufacturer
    {
       long Id {get; set;}
       String Name {get; set;}
    }
    
    0 讨论(0)
  • 2020-12-02 16:49

    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.

    0 讨论(0)
提交回复
热议问题