简体   繁体   中英

How to edit a cell value while databinding a datagridview?

I have a list of objects (type A) that act as a datasource for my datagridview. A property of type A is a list of objects from type B.

I want to show the list of type B in a cell. I want to do this with the Description property of object B. The descriptions (of object B) shown in the datagridview are comma seperated.

Which event do I have to hook into, to edit the cell value? I don't want to add a property to my object, because then I am going to modify my object for UI representation and this I don't want.

Finally I found something. I don't know whether this is the correct way, but it works for me now. Here is what I have done:

1) I have set the property VirtualMode to true of the datagridview. 2) I handle the CellValueNeeded event. In this event handler I check for the column index and I set the value:

private void myDataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
    if (e.ColumnIndex == 3)
    {
        // _appointments is a member variable which is the datasource of the grid
        Appointment appointment = _appointments[e.RowIndex];

        IList<DisciplineType> disciplines = appointment.GetDisciplines();

        for (int i = 0; i < disciplines.Count; i++)
        {
            if (i > 0)
                e.Value += ", " + disciplines[i].Description;
            else
                e.Value += disciplines[i].Description;
        }
    }
}

Hope this helps someone else too. Or if you have a better solution, please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM