DataGridViewColumn.DataPropertyName Property

跟風遠走 提交于 2019-12-01 04:12:29

DataGridView doesn't support databinding to child properties. For more info, check this post

I like the solution that uses the CellFormatting event.

In case you want to use many child elements like this:

class MyClass
{
   public int Id;
   public MyOtherClass OtherClass;
}

class MyOtherClass
{
   public string Name;
   public int Number;
}

How about

1st solution Set value for each cell in some event (mabye other one is better), manually, after setting datasource, for example:

private void dgv_CellFormatting( object sender, DataGridViewCellFormattingEventArgs e )
{
   MyClass data = dgv.Rows[ e.RowIndex ].DataBoundItem as MyClass;

   dgv.Rows[ e.RowIndex ].Cells[ "colName" ].Value = data.OtherClass.Name;
   dgv.Rows[ e.RowIndex ].Cells[ "colNumber" ].Value = data.OtherClass.Number;
}

2nd solution What about creating a DataTable from the data and then bind it?

I'd be thankful for any opinion ;-)

user218447

Problem nr.1:

Try to do the following:

  1. extend MyOtherClass from Object (this step might not be needed)

  2. and override, or create, method ToString().

That should do it.

It sounds like the DataGridView's virtual mode would solve your problem. In virtual mode, the DataGridView will fire an event whenever it needs to display a cell. The event lets you populate the cell however you please. The advantage of virtual mode is the system only needs to pull the data that's actually being displayed, so there's no slow start-up time while you load everything.

    private void my_init_function() {
        datagridview.VirtualMode = true;
        datagridview.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(datagridview_CellValueNeeded);
    }

    private void datagridview_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
    {
        e.Value = get_my_data(e.RowIndex, e.ColumnIndex);
    }
Ricardo Wasniewski

The way of databinding a specific column of a datagrid to a child property of the datagrid's datasource is using the DataGridView.Column.Tag property, along with the ToString() override method inside the child object. It goes as follows:

public class Car
{
    public int Id { get; set; }

    public int Name { get; set; }

    public string Colour { get; set; }

    public Wheel Wheel { get; set; }
}

public class Wheel 
{
    public string WheelName { get; set; }

    public override string ToString()
    {
        return WheelName;
    }
}

public class Main
{
   private void LoadGrid(List<Car> data)
   {
       this.dataGridView.Columns["Wheel"].Tag = "WheelName";
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!