Search code examples
c#winformsdatagridviewdatagridviewcolumn

Add a column with derived data to a DataGridView


I have a datagridview bound to a list of "CarColor" objects. I am attempting to add an extra column to the dataGridView that takes the Name property of each CarColor and displays the localized version.

Currently I have an extension method that creates the column and populates it with the correct values but every time the dataGridView changes visibility or data, all the cells in the Localized Name column become empty. Before now I've managed a workaround by running the extension method on the dataGridView's VisibileChanged and DataSourceChanged events. This is cumbersome, especially if I am trying to affect a DataGridView in another control (such as a dialog).

I have read that using a DataGrid is an option, via setting the "Expression" value of a new column. However, I don't know if it's possible to convert a list to a DataGrid, or convert a DataGridView into a DataGrid.

How can I ensure that the values of the Localized Name table aren't erased?


Solution

  • If you have a List<CarColor> you don't need DataTable to add a new computed column. You can simply add a new property to the CarColor that returns the desired computed value or in your case the localized value of its Name property.

    public partial class CarColor
    {  
        publlic string LocalizedName
        {
            get
            {
                return GetLocalizedName(this.Name);
            }
        }
    
        private string GetLocalizedName(string name)
        {
            // put the logic for localizing the name here
        }
    }
    

    Note:

    • I wrote it partial, so you can let the original CarColor class untouched, just add this partial in the same namespace, or if you prefer, simply add body code of the class to the original CarColor.

    • If CarClass in not your class and you van not change it's code, yo can create a ViewModel class for CarColor and use the same idea to represent that property.